Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Java programs crash when exceptions must always be caught? [duplicate]

Forgive me if this is a stupid question, but as far as I know, all Java exceptions must be caught and handled. For example, something like this would create a compiler error:

public String foo(Object o) {
    if (o instanceof Boolean) {
        throw new Exception();
    }
    return o.toString();
}

Because the method foo() didn't add a throws clause.
However, this example would work (unless either the method foo() didn't have a throws clause or the method bar() didn't surround usage of foo() in a try/catch block):

public String foo(Object o) throws Exception {
    if (o instanceof Boolean) {
        throw new Exception();
    }
    return o.toString();
}

public void bar(Object o) {
    try {
        String s = foo(o);
    }
    catch (Exception e) {
        //...
    }
    //...
}

At the end, sometimes a Java program still sometimes crashes due to an unhandled exception.

How does this happen?

like image 657
Greg Whatley Avatar asked Jun 01 '15 02:06

Greg Whatley


2 Answers

You don't have to handle all kinds of exceptions.

Exceptions that inherit from java.lang.RuntimeException or java.lang.Error are so-called unchecked exceptions that can be caught by a try-catch construct, they don't have to be, though.

As you can see in the API docs of java.lang.Error, it does not inherit from java.lang.Exception. For this reason, it will not be caught by your try-catch block - you only look for java.lang.Exception and its subclasses.

Have a look at this article in the docs.

like image 50
TimoStaudinger Avatar answered Nov 03 '22 17:11

TimoStaudinger


Some exceptions can be unchecked, these are known as Runtime Exceptions. For example an IllegalArumentException is an unchecked exception because it is a descendant of java.lang.RuntimeException. You can read about it here.

like image 40
James Buck Avatar answered Nov 03 '22 15:11

James Buck