Signed in as:
filler@godaddy.com
Signed in as:
filler@godaddy.com
Exception Handling
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the difference between checked and unchecked exceptions.
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
ADVERTISEMENT
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions. Let's consider a scenario:
Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling in Java.
Do You Know?
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely:
The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.
The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.
Java provides five keywords that are used to handle the exception. The following table describes each.
KeywordDescriptiontryThe "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block alone. The try block must be followed by either catch or finally.catchThe "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.finallyThe "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not.throwThe "throw" keyword is used to throw an exception.throwsThe "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.
Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle the exception.
JavaExceptionExample.java
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
There are given some scenarios where unchecked exceptions may occur. They are as follows:
If we divide any number by zero, there occurs an ArithmeticException.
If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.
ADVERTISEMENTADVERTISEMENT
If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we have a string variable that has characters; converting this variable into digit will cause NumberFormatException.
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.
==============================================================================
Java try block is used to enclose the code that might throw an exception. It must be used within the method.
If an exception occurs at the particular statement in the try block, the rest of the block code will not execute. So, it is recommended not to keep the code in try block that will not throw an exception.
Java try block must be followed by either catch or finally block.
Java catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. However, the good approach is to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple catch block with a single try block.
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks:
But if the application programmer handles the exception, the normal flow of the application is maintained, i.e., rest of the code is executed.
Let's try to understand the problem if we don't use a try-catch block.
TryCatchExample1.java
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
As displayed in the above example, the rest of the code is not executed (in such case, the rest of the code statement is not printed).
There might be 100 lines of code after the exception. If the exception is not handled, all the code below the exception won't be executed.
Let's see the solution of the above problem by a java try-catch block.
TryCatchExample2.java
Output:
java.lang.ArithmeticException: / by zero
rest of the code
As displayed in the above example, the rest of the code is executed, i.e., the rest of the code statement is printed.
In this example, we also kept the code in a try block that will not throw an exception.
TryCatchExample3.java
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of the block code will not execute.
Here, we handle the exception using the parent class exception.
TryCatchExample4.java
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Let's see an example to print a custom message on exception.
TryCatchExample5.java
Output:
Can't divided by zero
Let's see an example to resolve the exception in a catch block.
TryCatchExample6.java
Output:
25
In this example, along with try block, we also enclose exception code in a catch block.
TryCatchExample7.java
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Here, we can see that the catch block didn't contain the exception code. So, enclose exception code within a try block and use catch block only to handle the exceptions.
In this example, we handle the generated exception (Arithmetic Exception) with a different type of exception class (ArrayIndexOutOfBoundsException).
TryCatchExample8.java
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Let's see an example to handle another unchecked exception.
TryCatchExample9.java
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code
Let's see an example to handle checked exception.
TryCatchExample10.java
ADVERTISEMENT
Output:
File saved successfully
============================================================================
A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block.
Let's see a simple example of java multi-catch block.
MultipleCatchBlock1.java
Output:
Arithmetic Exception occurs
rest of the code
MultipleCatchBlock2.java
Output:
ArrayIndexOutOfBounds Exception occurs
rest of the code
In this example, try block contains two exceptions. But at a time only one exception occurs and its corresponding catch block is executed.
MultipleCatchBlock3.java
Output:
Arithmetic Exception occurs
rest of the code
In this example, we generate NullPointerException, but didn't provide the corresponding exception type. In such case, the catch block containing the parent exception class Exception will invoked.
MultipleCatchBlock4.java
Output:
Parent Exception occurs
rest of the code
Let's see an example, to handle the exception without maintaining the order of exceptions (i.e. from most specific to most general).
MultipleCatchBlock5.java
Output:
Compile-time error
===============================================================================
In Java, using a try block inside another try block is permitted. It is called as nested try block. Every statement that we enter a statement in try block, context of that exception is pushed onto the stack.
For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while the outer try block can handle the ArithemeticException (division by zero).
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.
Let's see an example where we place a try block within another try block for two different exceptions.
NestedTryBlock.java
Output:
When any try block does not have a catch block for a particular exception, then the catch block of the outer (parent) try block are checked for that exception, and if it matches, the catch block of outer try block is executed.
If none of the catch block specified in the code is unable to handle the exception, then the Java runtime system will handle the exception. Then it displays the system generated message for that exception.
Let's consider the following example. Here the try block within nested try block (inner try block 2) do not handle the exception. The control is then transferred to its parent try block (inner try block 1). If it does not handle the exception, then the control is transferred to the main try block (outer try block) where the appropriate catch block handles the exception. It is termed as nesting.
NestedTryBlock.java
Output:
Java finally block is a block used to execute important code such as closing the connection, etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be printed regardless of the exception occurs or not.
The finally block follows the try-catch block.
Let's see the different cases where Java finally block can be used.
Backward Skip 10sPlay VideoForward Skip 10sADVERTISEMENT
Let's see the below example where the Java program does not throw any exception, and the finally block is executed after the try block.
TestFinallyBlock.java
Output:
Let's see the the fillowing example. Here, the code throws an exception however the catch block cannot handle it. Despite this, the finally block is executed after the try block and then the program terminates abnormally.
TestFinallyBlock1.java
Output:
Example:
Let's see the following example where the Java code throws an exception and the catch block handles the exception. Later the finally block is executed after the try-catch block. Further, the rest of the code is also executed normally.
TestFinallyBlock2.java
Output:
==============================================================================
In Java, exceptions allows us to write good quality codes where the errors are checked at the compile time instead of runtime and we can create custom exceptions making the code recovery and debugging easier.
The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The Exception has some message with it that provides the error description. These exceptions may be related to user inputs, server, etc.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to throw a custom exception. We will discuss custom exceptions later in this section.
ADVERTISEMENTADVERTISEMENT
We can also define our own set of conditions and throw an exception explicitly using throw keyword. For example, we can throw ArithmeticException if we divide a number by another number. Here, we just need to set the condition and throw exception using throw keyword.
The syntax of the Java throw keyword is given below.
throw Instance i.e.,
Let's see the example of throw IOException.
Where the Instance must be of type Throwable or subclass of Throwable. For example, Exception is the sub class of Throwable and the user-defined exceptions usually extend the Exception class.
In this example, we have created a method named validate() that accepts an integer as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.
TestThrow1.java
In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.
Output:
The above code throw an unchecked exception. Similarly, we can also throw unchecked and user defined exceptions.
If we throw a checked exception using throw keyword, it is must to handle the exception using catch block or the method must declare it using throws declaration.
TestThrow2.java
Output:
exception is everything else under the Throwable class.
TestThrow3.java
Output:
==============================================================================
An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method. If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack. This is called exception propagation.
TestExceptionPropagation1.java
Output:
exception handled
normal flow...
In the above example exception occurs in the m() method where it is not handled, so it is propagated to the previous n() method where it is not handled, again it is propagated to the p() method where exception is handled.
Exception can be handled in any method in call stack either in the main() method, p() method, n() method or m() method.
TestExceptionPropagation1.java
Output:
Compile Time Error
================================================================================
The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception. So, it is better for the programmer to provide the exception handling code so that the normal flow of the program can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers' fault that he is not checking the code before it being used.
Ans: Checked exception only, because:
Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.
Let's see the example of Java throws clause which describes that checked exceptions can be propagated by throws keyword.
Testthrows1.java
Output:
exception handled
normal flow...
===============================================================================
There are many rules if we talk about method overriding with exception handling.
Some of the rules are listed below:
Let's consider following example based on the above rule.
TestExceptionChild.java
Output:
TestExceptionChild1.java
Output:
TestExceptionChild2.java
Output:
TestExceptionChild3.java
Output:
TestExceptionChild4.java
Output:
TestExceptionChild5.java
Output:
=============================================================================
In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our own Exception is known as custom exception or user-defined exception. Basically, Java custom exceptions are used to customize the exception according to user need.
Consider the example 1 in which InvalidAgeException class extends the Exception class.
Using the custom exception, we can have your own exception and message. Here, we have passed a string to the constructor of superclass i.e. Exception class that can be obtained using getMessage() method on the object we have created.
In this section, we will learn how custom exceptions are implemented and used in Java programs.
Java exceptions cover almost all the general type of exceptions that may occur in the programming. However, we sometimes need to create custom exceptions.
Following are few of the reasons to use custom exceptions:
In order to create custom exception, we need to extend Exception class that belongs to java.lang package.
Consider the following example, where we create a custom exception named WrongFileNameException:
Let's see a simple example of Java custom exception. In the following code, constructor of InvalidAgeException takes a string as an argument. This string is passed to constructor of parent class Exception using the super() method. Also the constructor of Exception class can be called without using a parameter and calling super() method is not mandatory.
TestCustomException1.java
Output:
TestCustomException2.java
Output:
We use cookies to analyze website traffic and optimize your website experience. By accepting our use of cookies, your data will be aggregated with all other user data.