Java Exceptions: Throw, Try and Catch
Exceptions are used when writing code for "exceptional situations" such as:
- The user tried to open a file that doesn't exist
- There's an error in a configuration file
- A server could not be reached due to a network problem
When such event occur, it's appropriate to throw an exception. The statements below a throw statement are skipped:
Execution will continue as normal when the exception is caught. You catch an exception using try and catch in the following way:
If the exception isn't caught within the method, it will propagate to the previous method:
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.