How can Java programs crash when exceptions should always be caught?

Forgive me if this is a stupid question, but as far as I know, all Java exceptions should 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(); } 

Since the foo() method did not add a throws .
However, this example will work (if none of the foo() methods had a throws or the bar() method did not surround using foo() in a try/catch ):

 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) { //... } //... } 

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

How does this happen?

+5
source share
2 answers

You do not need 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 the try-catch construct, but they do not have to be.

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

See this article in the docs .

+5
source

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

+1
source

All Articles