Exception thrown in method - java

public class X {
public void foo() throws Exception{
System.out.print("hi ");
throw new Exception();
}
public static void main(String[] args) throws Exception {
X c = new X();
c.foo();
}
}
As in my foo() method I am throwing Exception and propagating the Exception by using throws. In my main() method I am again propagating my Exception.
When I compile it works fine.
My question is: why don't I need to handle this throw new Exception()? Who is taking care of this?

It will be thrown to the err console as your
main method declares "throws Exception".
Remove this and it won't compile anymore.

Every thread has a handler for uncaught exceptions—exceptions that terminate the thread. The default exception handler invokes printStackTrace() on the Throwable that terminates the thread, unless the error is an instance of ThreadDeath. You can change this behavior on a particular thread by setting a custom handler, for a group of threads by extending ThreadGroup, or for all threads by installing a default handler.

Related

Propogating checked exceptions to the caller thread

I have multiple methods running concurrently on different threads. If an exception occurs and isn't handled on any of the threads, I want it to propagate back to the calling method (see example below).
public class Main {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(3);
pool.execute(new Thread1Class());//Thread 1 of many
//...
}
}
class Thread1Class implements Runnable{
#Override
public void run() {
try {
throw new InterruptedException(); //How do I propogate this to the main method?
} catch (InterruptedException e) {
System.out.println("An unchecked exception was caught here");
}
}
}
The threads must implement Runnable since Callable will block the threads from running concurrently.
I followed the method of Overriding protected void afterExecute(Runnable r, Throwable t) shown as the accepted answer here: Handling exceptions from Java ExecutorService tasks. If I understand correct, this solution will only handle unchecked exceptions. How should I deal with the checked exceptions?
If I understand correct, this solution will only handle unchecked exceptions. How should I deal with the checked exceptions
No, the afterExecute(Runnable, Throwable) would catch any RuntimeException or checked exception. According to the docs at https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html
If non-null, the Throwable is the uncaught RuntimeException or Error that caused execution to terminate abruptly.
Edit:
Sorry for the misunderstanding,
If you want to propagate the checked exception to the caller, you would need to wrap it in a RuntimeException
InterruptedException a;
throw new RuntimeException("wrapped", a);
The executor:
protected void afterExecute(Runnable r, Throwable t){
Throwable root = t.getCause();
}
Or you could create your own runtime exception type.

What happens when try with resources throws an exception along with an exception when closing the resources automatically

Imagine a situation where, an exception occurs in try with resources block. It will call the close method to close the resources. What happens if close method also throws an exception. Which exception is thrown.?
The answer is: Both! The first one is just a bit more prominent.
First your inner exception will be thrown. Then the close() method of the Closeable will be called and if that one does also throw its exception, it will be suppressed by the first one. You can see that in the stack trace.
Test code:
public class DemoApplication {
public static void main(String[] args) throws IOException {
try (Test test = new Test()) {
throw new RuntimeException("RuntimeException");
}
}
private static class Test implements Closeable {
#Override
public void close() throws IOException {
throw new IOException("IOException");
}
}
}
Console log:
Exception in thread "main" java.lang.RuntimeException: RuntimeException
at DemoApplication.main(DemoApplication.java:15)
Suppressed: java.io.IOException: IOException
at DemoApplication$Test.close(DemoApplication.java:22)
at DemoApplication.main(DemoApplication.java:16)
If you like to, you can get the suppressed exception with exception.getSuppressed().

what does it mean -> public static void main(String[] args) throws IOException

When we write this ->void add() throws ArithmeticException. It indicated methos add may or may not throw an ArithmeticException. so the calling method has to write try and catch block in order to handle this exceprtion. Then what does it mean when we write this -> public static void main(String[] args) throws IOException. even if main method throws IOException there is no calling methosd to handle it. so what does it mean when we write main methos throws an exception?
Because IOException is a checked Exception and main is just a method like any other, than if a checked Exception is thrown in a method, it has to be declared in the method signature. In other words, main might be the entry point, but it could also be called like any method, and even as an entry point it's called by other code in the JVM.
The main method is not really any different from any other method. It is only special because it is defined as the entry point of your application. In the event that it throws an exception, and there is no handler, your program will crash and cease to function. However, there are scenarios where the main method can be handled. For example:
public class a{
public static void main(String[] args)throws IOException{
throw IOException;
}
}
//some other class:
String[] args = {};
new a().main(args);
what does it mean -> public static void main(String[] args) throws
IOException
it means, the main method is not catching any exceptions, instead it handles the IOException by throwing it to the source which invoked the main method.
You throw Exception if you want it to be handled by higher function or calling function.
remember, when you throw Exception The exception doesn't just disappear, It stil has to be handled by calling function. otherwise it'll crash the program.
Example :
public void iThrowException() throws Exception{
throw new Exception("It has to be handled!");
}
whenever you want to call this method you should call inside try/catch block
like this
public void iWillHandleIt(){
try{
iThrowException();
}catch(Exception e){
System.err.println("Exception caught: "+e);
}
}
As in your case if you throw Exception from main method, caller of main() method i.e.; JVM need to handle the exception. otherwise it will lead to crash.
you'll get better idea if you go throw Read more about Checked and UncheckedExceptions here
public static void main(String[] Args) throws IOException
{
......
}
where this specifies that the method may going to throws IOException and insist the compiler that the block which is calling this method needs some special attention towards this regarding handling or again throwing back.
throws IOException: the logic present within the main method performs some I/O related tasks, and to make sure that the program does not crash owing to some I/O related issues, this work as a fail- safe. Alternately, wrapping the responsible code within a try- catch construct also works.

Why java allows run() to throw Unhanlded Exception while restricting Handled ones?

It is sayed that the run does't throw Handled Exceptions. JVM simply ignores them. So I threw UnHandled Exception (ArithmeticException). But the same thing happened for it as well.
I know that it is rediculous to try to catch the excpetion from a thread that has been started by the catch clause marked as XXX. Because the excution may already passed that line.
But I wanna know why java allows run to throw Unhanlded Exception while restricting Handled ones and what is happening additionally when run() throwing Unhandled Exception?
Parent Thread
public class Parent {
public static void main(String[] args) {
Child child = new Child();
Thread chThread = new Thread(child);
try {
chThread.start();
} catch (Exception e) { // XXX mark
System.err.println("XXX");
e.printStackTrace();
}
}
Child Thread
public class Child implements Runnable {
#Override
public void run() throws ArithmeticException{
method0(); // line 8
}
public void method0(){
int i = 0/0; // line 12
}
}
java.lang.Thread
public class Thread implements Runnable {
public void run() {
if (target != null) {
target.run(); // line 619
}
}
}
StackTrace
Exception in thread "Thread-0" java.lang.ArithmeticException: / by zero
at seperateStacksPerThread.Child.method0(Child.java:12)
at seperateStacksPerThread.Child.run(Child.java:8)
at java.lang.Thread.run(Thread.java:619)
The signature of run() does not include a checked exception. As a result you can not override it to throw a checked exception (when you override you can never be more restrictive).
But throwing an unchecked exception is allowed as it is not part of the signature (no one is required to catch it).
When you throw the arithmetic exception it is part of the stack trace of a different thread.
Notice that it says:
Exception in thread "Thread-0" java.lang.ArithmeticException: / by zero
And not: Exception in thread "main" java.lang.ArithmeticException: / by zero
Now why are checked exceptions not allowed, it is a design decision and I think it is because no one can catch them anyway as a thread is a separate flow of excecution.
Firstly, all methods may throw unchecked exceptions.
Next, the simple reason run() doesn't throw checked exceptions is there's no one there to catch them! The method is called from within the started thread as its "main" method - it's the top level entry point. There's nothing above it to deal with an exception, so there's no point in declaring a method that throws an exceptions.

Java exception handling

I have the following code. In that fn2 is actually throwing an exception and it is caught in the function itself. In the function fn1 the compiler is complaining about unhandled exception since fn2 is declared to be throwing an Exception.
Why it is so? Since the exception is caught inside fn2 it shouldn't be complaining right?
Please explain the behavior.
public class ExepTest {
/**
* #param args
*/
public static void main(String[] args) {
ExepTest exT = new ExepTest();
exT.fn1();
}
public void fn1(){
fn2();//compilation error
}
public void fn2() throws Exception{
try{
throw new Exception();
}
catch(Exception ex){
System.out.println("Exception caught");
}
}
}
Compiler doesn't/can't know that at runtime no exception will be throwed by fn2() since it's declared that it may throw an Exception, that's why you got an error.
Remove the throws Exception from fn2() signature
The signature of the method fn2 is all that matters here. In that signature you declare that fn2 may throw an Exception. Any code that calls a method that may throw an Exception must handle the eexception.
public void fn2() throws Exception. The compiler see that declaration and expect each caller to fn2 to handle / rethrow the exception.
Exception is thrown BY fn2, not inside it. So it will be actually thrown where it is called. Since it is called in fn1, it is behaving like this.
You need to surround the call to fn2() in a try-catch block, or declare that fn1 also throws an exception.
public void fn1(){
fn2();//compilation error
}
public void fn2() throws Exception{
try{
throw new Exception();
}
catch(Exception ex){
System.out.println("Exception caught");
}
}
}
Here compiler will not recognize that you have handled exception or not. It just assumes that fn2 throws exception as you have declared to be and that's why it's showing error.
To run program either remove throws Exception from fn2 or write throws Exception in fn1 or handle it in try..catch in fn1.

Categories