Exceptions
Contents
Exceptions are useful to programmatically handle both foreseen, and (somewhat) unforeseen errors.
|
|
Throwing Exceptions
throw new SomeExceptionClass(...)
Everything is an Exception
That is, Exception
is the base class of all exceptions.
We could technically catch every single possible exception with ... } catch (Exception e) { ... }
|
|
Note: This is discouraged, as you lose scope of which exception was raised.
Defining Custom Exceptions
To define a custom Java exception, we need to extend the abstract Exception
class
|
|
We can then throw, and catch this exception.
|
|
Delegating raised exceptions to other code
Consider the function
|
|
If OpenFile
has the possibility to throw an exception (i.e. FileNotFoundException
), then we will have to acknowledge that possibility in our code
|
|
If we wanted to catch the exception outside of our tryDoIt
function, we would have to reraise the exception.
|
|
However in Java, we can add a hint to the method definition that it may throw the FileNotFoundException
|
|
By using the throws
keyword, we can delegate the handling of the exception to another function.
Exceptions and Inheritance
Inherited classes must not throw more exceptions than those defined by their parent - only subsets.