Reputation: 1
So basically, if we use the throws
keyword in a method signature, we are passing the handling responsibility to the caller method; if we use the throw
keyword, we are explicitly throwing an exception. Both throws
and throw
are not ways to handle an exception. Only the statements in the catch
block can be considered the way to handle an exception since our program won't terminate since we have handled the exception. Am I getting it correctly? Since in Java interviews we are always asked how do we handle exceptions in Java.
Upvotes: 0
Views: 1088
Reputation: 358
Shortly, answer ordered like that:
Please note, that this list is more about JVM mechanisms rather then 'frameworks'.
If you want more I believe you can play with code below and see docs of used methods and classes.
public static void main(String[] args) throws InterruptedException {
System.out.println("START main");
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
System.err.println("Thread.setDefaultUncaughtExceptionHandler");
});
Thread.currentThread().setUncaughtExceptionHandler((t, e) -> {
System.err.println("thread[main].uncaughtException");
});
java.util.concurrent.ThreadFactory threadFactory = r -> {
ThreadGroup g = new ThreadGroup("eta") {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.err.println("threadGroup.uncaughtException");
}
};
Thread thread = new Thread(g, r);
thread.setUncaughtExceptionHandler((t, e) -> {
System.err.println("thread.uncaughtException");
});
return thread;
// return new Thread(r);
};
threadFactory.newThread(() -> {
System.out.println("START newThread logic");
throw new RuntimeException();
}).start();
if (true) throw new RuntimeException();
}
Ouputs:
START main
START newThread logic
thread[main].uncaughtException
thread.uncaughtException
Upvotes: 0
Reputation: 310993
This is correct.
When an exception is thrown, you have only two options - either catch
ing or allowing it to be thrown upwards to the caller. Ultimately, if it's never caught, the thread will terminate.
Upvotes: 1
Reputation: 1
Exceptions are handled with try-catch
block which wraps the code throwing an exception. No matter how it's issued with throw
clause or indirectly via calling a method which has throws
in the method signature. If the method throws an exception and does not declare it in the method signature then this is kind of unchecked exceptions. These exceptions are handled the same way as checked exceptions that you have to catch or declare to be thrown.
See more about exceptions in Java Tutorial.
Upvotes: 0
Reputation: 11
Yeah I would agree mostly agree.
Upvotes: 1