- Java lang exception hierarchy
- Checked and Unchecked exceptions
- Java Exceptions Hierarchy Explained
- Java Exceptions Hierarchy
- Java Errors vs Exceptions
- Checked vs Unchecked Exceptions
- Checked Exceptions
- Unchecked Exceptions
- Track, Analyze and Manage Errors With Rollbar
- Exception Hierarchy in Java
- Errors
- Exceptions
- Custom Exceptions
- 1. Checked Exceptions
Java lang exception hierarchy
Java exception handling is used to handle error conditions in a program systematically by taking the necessary actions. Therefore stated simply, the exception-handling capability of Java makes it possible for us to: All exception types are subclasses of the Java built-in class java.lang.Throwable (which is a subclass of java.lang.Object). Thus, Throwable is at the top of the exception class hierarchy. Immediately below Throwable are two subclasses that partition exceptions into two distinct branches: java.lang.Exception and java.lang.Error. The objects that inherit from the Throwable class include direct descendants (objects that inherit directly from the Throwable class) and indirect descendants (objects that inherit from children or grandchildren of the Throwable class). Figure 1 below illustrates the class hierarchy of the Throwable class and its most significant subclasses.
Figure 1: Class Hierarchy of the java.lang.Throwable class
java.lang.Exception
One branch is headed by java.lang.Exception. This class is used for exceptional conditions that user programs should catch. This is also the class that we will subclass to create our own custom exception types. There is an important subclass of Exception, called java.lang.RuntimeException. Exceptions of this type are automatically defined for the programs that we write and include things such as division by zero, invalid array indexing etc. E.g. ArithmeticException , ArrayIndexOutOfBoundsException , IOException etc.
java.lang.Error
The other branch is led by java.lang.Error, which defines exceptions those are not expected to be caught under normal circumstances by our program. Exceptions of type Error are used by the Java runtime system to indicate errors having to do with the runtime environment, itself. Stack overflow is an example of such an error. Exceptions of type Error are typically created in response to catastrophic failures that cannot usually be handled by user program. E.g. VirtualMachineError , OutOfMemoryError , StackOverflowError etc.
Therefore, there are three types of Java exceptions: Exception, Error, and RuntimeException (though it is a subclass of Exception).
Checked and Unchecked exceptions
When an exception occurs, it must be dealt with in either a “try/catch” block or by declaring a “throws” in a method. This concept is called to catch or to declare an exception object. Now during compile time whether to catch/declare an exception or not, based on this, Java also defines two kinds of exceptions called checked and unchecked exceptions:
∅ Checked exceptions: Compiler will check that we have done one of the two things (catch, or declare). So these are called checked exceptions. Exceptions that inherit from the java.lang.Exception class (except RuntimeException and its subclasses) are checked exceptions. Checked Exceptions force programmers to deal with the exception that may be thrown by the API, either in a catch clause or by forwarding it outward with the throws clause. E.g. Exception, IOException, FileNotFoundException, InterruptedException, ClassNotFoundException etc.
∅ Unchecked exceptions: The class java.lang.RuntimeException and its subclasses are not checked by compiler (even though we can choose to catch, or declare, it is not required). So, these two are called unchecked exceptions. Unlike checked exceptions the subclasses of RuntimeException do not need to be caught at compile time. E.g. ArithmeticException, ArrayIndexOutOfBoundsException, ClassCastException, NullPointerException, NumberFormatException etc.
Java Exceptions Hierarchy Explained
In Java “an event that occurs during the execution of a program that disrupts the normal flow of instructions” is called an exception. This is generally an unexpected or unwanted event which can occur either at compile-time or run-time in application code. Java exceptions can be of several types and all exception types are organized in a fundamental hierarchy.
Java Exceptions Hierarchy
The class at the top of the exception class hierarchy is the Throwable class, which is a direct subclass of the Object class. Throwable has two direct subclasses — Exception and Error.
The diagram below shows the standard exception and error classes defined in Java, organized in the Java exceptions hierarchy:
Figure 1: Exceptions hierarchy in Java
The Exception class is used for exception conditions that the application may need to handle. Examples of exceptions include IllegalArgumentException , ClassNotFoundException and NullPointerException .
The Error class is used to indicate a more serious problem in the architecture and should not be handled in the application code. Examples of errors include InternalError , OutOfMemoryError and AssertionError .
Exceptions are further subdivided into checked (compile-time) and unchecked (run-time) exceptions. All subclasses of RuntimeException are unchecked exceptions, whereas all subclasses of Exception besides RuntimeException are checked exceptions.
Java Errors vs Exceptions
According to the official documentation, an error “indicates serious problems that a reasonable application should not try to catch.” This refers to problems that the application can not recover from — they should be dealt with by modifying application architecture or by refactoring code.
Here is an example of a method that throws a error, which is not handled in code:
public static void print(String myString)
In this example, the recursive method “print” calls itself over and over again until it reaches the maximum size of the Java thread stack, at which point it exits with a StackOverflowError :
Exception in thread "main" java.lang.StackOverflowError at StackOverflowErrorExample.print(StackOverflowErrorExample.java:6)
As seen above, the method throws the error during execution but does not handle it in code — the program simply exits when the error occurs since it is irrecoverable and requires a change in the code itself.
Exceptions, on the other hand, indicate “conditions that a reasonable application might want to catch.” These could include problems that can occur at compile-time (checked exceptions) or run-time (unchecked exceptions) and can happen rather frequently in most applications — especially during development. Checked exceptions should be handled in application code, whereas unchecked exceptions don’t need to be handled explicitly.
Checked vs Unchecked Exceptions
Checked Exceptions
Exceptions that can occur at compile-time are called checked exceptions since they need to be explicitly checked and handled in code. Classes that directly inherit Throwable — except RuntimeException and Error — are checked exceptions e.g. IOExceptio n, InterruptedException etc.
Here is an example of a method that handles a checked exception:
public void writeToFile() < try (BufferedWriter bw = new BufferedWriter(new FileWriter("myFile.txt"))) < bw.write("Test"); >catch (IOException ioe) < ioe.printStackTrace(); >>
In this example, both statements within the try block (the instantiation of the BufferedWriter object and writing to file using the object) can throw IOException , which is a checked exception and therefore needs to be handled either by the method or its caller. In the example, IOException is handled within the method and the exception stack trace is printed to the console.
Furthermore, the BufferedWriter object is a resource, which should be closed when it is no longer needed and closing it can throw an IOException as well. In such cases where closing resources themselves can throw exceptions, using a try-with-resources block is best practice since this takes care of the closing of resources automatically. The example shown earlier uses try-with-resources for exactly this reason.
Unchecked Exceptions
Unchecked exceptions can be thrown «at any time» (i.e. run-time). Therefore, methods don’t have to explicitly catch or throw unchecked exceptions. Classes that inherit RuntimeException are unchecked exceptions e.g. ArithmeticException , NullPointerException .
Here is an example of a method that throws an unchecked exception (NullPointerException) which is not handled in code:
public void writeToFile() < try (BufferedWriter bw = null) < bw.write("Test"); >catch (IOException ioe) < ioe.printStackTrace(); >>
When the above method is called, a NullPointerException is thrown because the BufferedWriter object is null:
Exception in thread "main" java.lang.NullPointerException at IOExceptionExample.writeToFile(IOExceptionExample.java:10) at IOExceptionExample.main(IOExceptionExample.java:17)
As mentioned, since NullPointerException is an unchecked exception, it did not need to be handled in code — only the checked exception (IOException) was handled.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing errors easier than ever. Try it today!
«Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind.»
Exception Hierarchy in Java
Whenever any unexpected event like if required Index is more than the array size happens, it results in the stopping of the program. The name of this condition is an “Exception”.
There are many types of exceptions occurred in java, and there is a certain hierarchy followed by java. We will be exploring this hierarchy through this blog.
“Throwable class” is the topmost class in the hierarchy. It is mainly divided into 2 types which are Exception class and Error class.
Errors
Errors are problems that are happening due to failures in the system or Java virtual machine (JVM). One common example of an error can be a system crash. Errors can only occur when we are running a program (runtime), this is the reason error is an unchecked type.
Here is an example of an Error:
Explanation:
In the above code, we can see that the print function is calling itself again and again, there is no ending for this function call. This results in the filling of the Stack and we get the “StackOverflowError”. It cannot be solved directly with the use of debugging.
Exceptions
Exceptions are errors happening due to problems in the code/program. It can occur at either runtime (unchecked exception) or compile time (checked exception). The checked exception are needed to be corrected through the program although unchecked exceptions need not be solved precisely.
Here is an example of an Exception:
//Since dividing any number by 0 will result into an infinite number so we will give 0 as second number
Explanation:
In the above code, we are dividing any particular numeric value with 0. This is not possible as it will result in an infinite number. As division is an Arithmetic Operation and it cannot be performed in this case therefore the “ArithmeticException” occurs.
Custom Exceptions
“Custom” word states that the complete functionality of any application is designed by the person . So custom exceptions are created by the coder according to the need of the program. Therefore it is also known as user defined exceptions. This is one of the advantages that java includes, i.e, giving the choice to programmers to create their exceptions.
Explanation:
In the starting, we are creating a child class of Exception class naming it as invalidgender class. Now we will create a constructor of the invalidgender class, and call the constructor of the Exception class using super keyword.
While declaring the main function we will write throws invalidgender, throws keyword will help the program to get the information about the invalidgender exception.
If-else condition is used to find whether the written gender is either male or female. If it is either male or female we will go inside the if-condition and print the entered the gender. Otherwise we are going to call the invalidgender exception.
The argument passed as an string inside the invalidgender exception will be printed.
There are two types of predefined exceptions in java:
1. Checked Exceptions
Exceptions which are having the probability to arise while compiling are known as checked exceptions. These type of exceptions are needed to be handled specifically and can’t be ignored. You can handle checked exceptions using try-catch block.
For Example: If the user is trying to access a file which is not even created yet, then the program will return a File Not Found Exception.