Types of Exceptions
Compile Time Exception
Exceptions are checked during compile time
To be compiled successfully, the code must handle exception
- Try Catch
- Throw Exception
Otherwise, it will throw an exception during compile.
Runtime Exception
Runtime exceptions are not checked during compile.
Therefore, the developer must be able to except exceptions and be able to handle them
Most common exceptions are NullPointerException
NullPointerException happens when trying to access a null object
Throwing an Exception
see example below
throw new Exception();
throw new NullPointerException();
You can include message too.
throw new Exception("some message 1");
throw new NullPointerException("some message 2");
Handling Exceptions
Try, Catch, finally
There can be multiple catch block for try catch.
It is usual to go from specific exception to general exception. (see example below)
1
2
3
4
5
6
7
8
9
try{
//code
}
catch(NullPointerException e) {
//handle error
}
catch(Exception e) {
//handle error
}
finally block runs even if the exception is not handled.
Thus, it can be used for cleanup process.
Postponding Exceptions
See the example below
1
2
3
public void someFunction() throws NullPointerException {
// code
}
Note for CS2114 students
You should test exception if you have exception handling code in your test.