7

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?

Greg Whatley
  • 1,020
  • 1
  • 13
  • 32

2 Answers2

7

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.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
1

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.

James Buck
  • 1,640
  • 9
  • 13