Java Reference
In-Depth Information
Exception Handling
When an exception occurs, the program terminates with an error message. This is ideal in
development as it allows us to identify and fix errors. In production, however, it will appear
as if the program has crashed, which does not reflect well on a ninja programmer.
It is possible to handle exceptions gracefully by catching the error. Any errors can be hidden
from users, but still identified. We can then deal with the error appropriately‍―perhaps even
ignore it―and keep the program running.
try , catch , and finally
If we suspect a piece of code will result in an exception, we can wrap it in a try block.
This will run the code inside the block as normal, but if an exception occurs it will pass
the error object that is thrown on to a catch block. Here is a simple example using our
squareRoot() function from earlier:
function imaginarySquareRoot(number) {
"use strict";
try {
return String(squareRoot(number));
} catch(error) {
return squareRoot(-number)+"i";
The code inside the catch block will only run if an exception is thrown inside the try
block. The error object is automatically passed as a parameter to the catch block. This al-
lows us to query the error name, message, and stack properties and deal with it appropriately.
In this case, we actually return a string representation of an imaginary number:
imaginarySquareRoot(-49) // no error message shown
<< "7i"
A finally block can be added after a catch block. This will always be executed after
the try or catch block, regardless of whether an exception occurred or not. It is use-
Search WWH ::

Custom Search