Core Java - Exceptions Handling
What is an exception?
An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs, program execution gets terminated. In such cases, we get a system generated error message.
The good thing about exceptions is that java developer can handle these exceptions in such a way so that the program doesn’t get terminated abruptly and the user gets a meaningful error message.
Why we use exception handling?
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., it will not execute statements 6 to 10. However, when we perform exception handling, the rest of the statements get executed. That is why we use exception handling.
Explain the Hierarchy of Exception classes.
All exception types are subclasses of class Throwable, which is at the top of the exception class hierarchy.
Types of Exceptions
In Java, exceptions broadly can be categories into checked exception, unchecked exception and error based on the nature of exception.
- Checked Exception
- Unchecked Exception
- Error
The exception that can be predicted by the JVM at the compile time for example : File that need to be opened is not found, SQLException etc. These type of exceptions must be checked at compile time.
Unchecked exceptions are the class that extends RuntimeException class. Unchecked exception are ignored at compile time and checked at runtime. For example : ArithmeticException, NullPointerException, Array Index out of Bound exception. Unchecked exceptions are checked at runtime.
They typically ignore errors in code because we can rarely do anything about an error. For example, if stack overflow occurs, an error will arise. We cannot handle this type of error in the code.
Explain the class java.lang.Exception.
There are some important methods available in the Throwable class which are as follows:
- public String getMessage() – Provides information about the exception that has occurred through a message, which is initialized in the Throwable constructor.
- public Throwable getCause() – Provides root cause of the exception as represented by a Throwable object.
- public void printStackTrace() – Used to display the output of toString() along with the stack trace to System.err (error output stream).
- public StackTraceElement [] getStackTrace() – Returns an array with each element present on the stack trace. The index 0 element will symbolize the top of the call stack, and the last element of array will identify the bottom of the call stack.
There are mainly two types of exceptions in Java as follows:
- Checked exception
- Unchecked exception
How to Handle Exception?
Java provides controls using a special type of keywords to handle exception in the program. We list these keywords below.
- try : This keyword is used to enclose the suspected code.
- catch: This keyword acts as to enclose the exception handler code.
- finally: It is used to execute the must have necessary code. Mostly used to clean-up the unused object references.
- throw:This keyword is used to throw the exception object explicitly.
- throws: We use this keyword to inform about the exceptions declared at the method declaration part.
Explain try
and catch
Block.
Try and catch both are Java keywords and used for exception handling. The try block is used to enclose the suspected code. Suspected code is a code that may raise an exception during program execution.
For example, if a code raise arithmetic exception due to divide by zero then we can wrap that code into the try block.
try{
int a = 10;
int b = 0
int c = a/b; // exception
}
The catch block also known as handler is used to handle the exception. It handles the exception thrown by the code enclosed into the try block. Try block must provide a catch handler or a finally block. We will discuss about finally block in our next tutorials.
The catch block must be used after the try block only. We can also use multiple catch block with a single try block.
try{
int a = 10;
int b = 0
int c = a/b; // exception
}catch(ArithmeticException e){
System.out.println(e);
}
try-catch Syntax
To declare try catch block, a general syntax is given below.
try{
// suspected code
}catch(ExceptionClass ec){
// exception handler code.
}
Exception handling is done by transferring the execution of a program to an appropriate exception handler (catch block) when exception occurs.
Example: Handling Exception
Now lets understand the try and catch by a simple example in which we are dividing a number by zero. The code is enclosed into try block and a catch handler is provided to handle the exception.
class Excp
{
public static void main(String args[])
{
int a,b,c;
try
{
a = 0;
b = 10;
c = b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}
------------------------ OUTPUT ----------------------
Divided by zero After exception is handled
Explanation
An exception will thrown by this program as we are trying to divide a number by zero inside try block. The program control is transferred outside try block. Thus the line "This line will not be executed" is never parsed by the compiler. The exception thrown is handled in catch block. Once the exception is handled, the program control is continue with the next line in the program i.e after catch block. Thus the line "After exception is handled" is printed.
Multiple catch blocks
A try block can be followed by multiple catch blocks. It means we can have any number of catch blocks after a single try block. If an exception occurs in the guarded code(try block) the exception is passed to the first catch block in the list. If the exception type matches with the first catch block it gets caught, if not the exception is passed down to the next catch block. This continue until the exception is caught or falls through all catches.
Multiple Catch Syntax
To declare the multiple catch handler, we can use the following syntax.
Now lets see an example to implement the multiple catch block that are used to catch possible exception.
The multiple catch blocks are useful when we are not sure about the type of exception during program execution.
Examples for Multiple Catch blocks
In this example, we are trying to fetch integer value of an Integer object. But due to bad input, it throws number format exception.
Number Format Exception java.lang.NumberFormatException: For input string: "abc"
In the above example, we used multiple catch blocks and based on the type of exception second catch block is executed.
Example: Multiple Exception
Lets understand the use of multiple catch handler by one more example, here we are using three catch handlers in catch the exception.
NOTE : At a time, only one exception is processed and only one respective catch block is executed.
Example for Unreachable Catch block
While using multiple catch statements, it is important to remember that sub classes of class Exception inside catch must come before any of their super classes otherwise it will lead to compile time error. This is because in Java, if any code is unreachable, then it gives compile time error.
Generic exception
Nested try statement
try statement can be nested inside another block of try. Nested try block is used when a part of a block may cause one error while entire block may cause another error. In case if inner try block does not have a catch handler for a particular exception then the outer try catch block is checked for match.
divide by zero array index out of bound exception
Important points to Remember
- If you do not explicitly use the try catch blocks in your program, java will provide a default exception handler, which will print the exception details on the terminal, whenever exception occurs.
- Super class Throwable overrides toString() function, to display error message in form of string.
- While using multiple catch block, always make sure that sub-classes of Exception class comes before any of their super classes. Else you will get compile time error.
- In nested try catch, the inner try block uses its own catch block as well as catch block of the outer try, if required.
- Only the object of Throwable class or its subclasses can be thrown.
Java throw, throws and finally Keyword
Throw, throws and finally
are the keywords in Java that are used in exception handling. The throw keyword is used to throw an exception and throws is used to declare the list of possible exceptions with the method signature. Whereas finally block is used to execute essential code, specially to release the occupied resources.
Now lets discuss each in details with the examples.
Java Throw
The throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception.
Syntax :
Creating Instance of Throwable class
We allows to use new operator to create an instance of class Throwable,
This constructs an instance of NullPointerException with name test.
Example throw Exception
In this example, we are throwing Arithmetic exception explicitly by using the throw keyword that will be handle by catch block.
In the above example the avg() method throw an instance of ArithmeticException, which is successfully handled using the catch statement and thus, the program prints the output "Exception caught".
Java throws
Keyword
The throws keyword is used to declare the list of exception that a method may throw during execution of program. Any method that is capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions are to be handled. A method can do so by using the throws keyword.
Syntax:
Example throws Keyword
Here, we have a method that can throw Arithmetic exception so we mentioned that with the method declaration and catch that using the catch handler in the main method.
Inside check function caughtjava.lang.ArithmeticException: demo
Difference between throw and throws
throw | throws |
---|---|
throw keyword is used to throw an exception explicitly. | throws keyword is used to declare an exception possible during its execution. |
throw keyword is followed by an instance of Throwable class or one of its sub-classes. | throws keyword is followed by one or more Exception class names separated by commas. |
throw keyword is declared inside a method body. | throws keyword is used with method signature (method declaration). |
We cannot throw multiple exceptions using throw keyword. | We can declare multiple exceptions (separated by commas) using throws keyword. |
finally
clause
A finally keyword is used to create a block of code that follows a try block. A finally block of code is always executed whether an exception has occurred or not. Using a finally block, it lets you run any cleanup type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of catch block.
Example finally Block
In this example, we are using finally block along with try block. This program throws an exception and due to exception, program terminates its execution but see code written inside the finally block executed. It is because of nature of finally block that guarantees to execute the code.
Out of try finally is always executed. Exception in thread main java. Lang. exception array Index out of bound exception.
You can see in above example even if exception is thrown by the program, which is not handled by catch block, still finally block will get executed.
Example : Finally Block
finally block executes in all the scenario whether exception is caught or not. In previous example, we use finally where exception was not caught but here exception is caught and finally is used with handler.
Exception caught finally is always executed.
User defined Exception subclass
Java provides rich set of built-in exception classes like: ArithmeticException, IOException, NullPointerException etc. all are available in the java.lang package and used in exception handling. These exceptions are already set to trigger on pre-defined conditions such as when you divide a number by zero it triggers ArithmeticException.
Apart from these classes, Java allows us to create our own exception class to provide own exception implementation. These type of exceptions are called user-defined exceptions or custom exceptions.
You can create your own exception simply by extending java Exception class. You can define a constructor for your Exception (not compulsory) and you can override the toString()
function to display your customized message on catch. Lets see an example.
Example: Custom Exception
In this example, we are creating an exception class MyException that extends the Java Exception class and
MyException[-10] is less than zero
Example: Custom Exception
Lets take one more example to understand the custom exception. Here we created a class ItemNotFound that extends the Exception class and helps to generate our own exception implementation.
ItemNotFound: Item Not Found
Points to Remember
- Extend the Exception class to create our own exception class.
- We don't have to implement anything inside it, no methods are required.
- We can have a Constructor if we want.
- We can override the toString() function, to display customized message.
Comments
Post a Comment