1. throw
operator
When an exception is caught by a catch
block, and until it is thrown to the Java machine, it is just an object that inherits Exception
(or rather, Throwable
). The exception object itself does not have any magical properties.
All the logic of how exceptions work is just a special way the Java machine behaves when an exception is thrown to it.
You can always rethrow a caught exception to the Java machine. To do this, you need to use the throw
operator:
throw exception;
Example:
Code | Console output |
---|---|
|
|
In this code, we caught an exception, displayed a message about it on the screen, and then rethrew it.
A rethrown exception cannot be caught by other catch
blocks in the same try
block.
2. Your exceptions
By the way, you can create an exception object yourself: it is just an object whose type is Exception
or a class that inherits it. And throw it.
It's easier than it sounds. Example:
Code | Console output |
---|---|
|
|
In the example above, we created a new exception object whose type is RuntimeException
and immediately threw it using the throw
operator.
It will be immediately caught by the catch
block, since RuntimeException inherits Exception
. The catch (Exception except)
code catches exception objects of all classes that inherit the Exception
class.
3. finally
keyword
Another important point. Sometimes a programmer needs to do perform some action regardless of whether an exception occurred in the code. For example, suppose we opened a file for writing. The opened file must be closed by calling close()
.
try
{
// Code where an exception might occur
}
catch(ExceptionType name)
{
// Exception handling code
}
finally
{
// Code that must executed no matter what happens
}
To perform these mandatory actions, another kind of block (finally
) was added to the try-catch
construct, thereby creating the try-catch-finally
construct. It looks like this:
Example:
FileInputStream source = null;
try
{
source = new FileInputStream("c:\\note.txt");
source.read();
}
catch(Exception except)
{
System.out.println("Caught the exception");
throw except;
}
finally
{
if (source != null)
source.close();
}
The code in the finally
block will execute in any case, regardless of whether there was an exception. Even if an exception is thrown and not caught, the finally
block will still execute.
By the way, if you do not want to catch an exception, but you do need a finally
block, use the shorthand notation for the try-catch-finally
construct: a try-finally
block. It looks something like this:
try
{
// Code where an exception might occur
}
finally
{
// Code that must executed no matter what happens
}
GO TO FULL VERSION