Java Exceptions: Throw, Try and Catch

Exceptions are used when writing code for "exceptional situations" such as:

When such event occur, it's appropriate to throw an exception. The statements below a throw statement are skipped:

statement throw new SomeException();

Execution will continue as normal when the exception is caught. You catch an exception using try and catch in the following way:

try { throw new SomeException(); } catch (SomeException e) { }

If the exception isn't caught within the method, it will propagate to the previous method:

void foo() { try { bar(); } catch (Ex e) { } } void bar() { baz(); } void baz() { throw new Ex(); }

Checked vs Unchecked Exceptions

If the exception being thrown is checked, the method needs to include a throws declaration to allow it to propagate. See Java Exception Types and Java Keyword: throws.

Uncaught Exceptions

If the exception is never caught a stack trace will be printed and the program (or at least the thread) will crash. For an example of how this might look, see Java: Stack trace.

Other Ways of Throwing

Apart from an explicit throw statement, an exception can be thrown due to programming errors, or calling an API method that throws an exception. A few examples:

Example: Invalid use of a null reference

String text = null;
text.length();

This will throw a NullPointerException.

Example: Calling an API method in a bad way

String text = "abc";
Integer.parseInt(text);

This will throw a NumberFormatException.

Comments

Be the first to comment!