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 statement statement throw new SomeException(); statement statement statement

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

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

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

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

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.

If the exception is never caught a stack trace will be printed and the program (or at least the thread) will crash. See Java: Stack trace.

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!