Chapter 10 |
Exception class hierarchy, checked and unchecked exceptions
All exception types are subclasses of the built-in class Throwable
. Thus, Throwable
is at the top of the exception class hierarchy.
Immediately below Throwable
are two subclasses: Exception
and Error
:
- Error indicate that something severe enough has gone wrong, the application should crash rather than try to handle the error.
- Exceptions are events that occurs in the code. A programmer can handle such conditions and take necessary corrective actions.
Both the Exception
class and the Error
class have a large number of subclasses. Check the documentation https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/Exception.html
.
Next, we are going to focus on the class Exception
, which can be divided into two categories: unchecked and checked exceptions.
Unchecked exceptions or runtime exceptions - an exception that occurs at the time of execution and ignored at the time of compilation (e.g. programming bugs, such as logic errors or improper use of an API). Since the compiler does not check them, these exceptions do not have to be indicated in the method header. Some unchecked exceptions defined in java.lang
are listed below.
All other exceptions are known as checked exceptions or compile time exceptions - an exception that is checked (notified) by the compiler at compilation-time, meaning that the compiler forces the programmer to check and deal with them:
- in a
try/catch
block or - declare it in the method header so that the caller of the method is informed of the exception. To declare an exception in a method, use the
throws
keyword in the method header. Athrows
clause lists the types of exceptions that a method might throw. If they are not, a compile-time error will occur. A list of checked exceptions is shown below:
For example, if we use BufferedReader
class in our program to read data from a file and the file specified in the constructor call does not exist, a FileNotFoundException
occurs, and the compiler prompts the programmer to handle the exception.
class FileReader2 { public static void main(String[] args) throws IOException { BufferedReader myReader = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), "UTF-8")); myReadLines(myReader); myReader.close(); } // remove the "throws IOException" and check the output of the program private static void myReadLines(BufferedReader myReader) throws IOException { while (true) { String line = myReader.readLine(); // can throw IOException if (line == null) break; // end of the file System.out.println(line); } } }
NB! IDEs usually generate the following code for the checked exceptions:
try { someMethodThatThrowsException(); } catch (Exception e) { e.printStackTrace(); // TODO autogenerated catch -- DO NOT DO LIKE THIS }
Such code without solutions to the exceptions does not solve the problem - rather use the throws
with the type of exceptions.
Chapter 10 |