Exceptions in Java
Exception Handling in Java is one of the effective means to handle the runtime errors so that the regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and handled by the program. When an exception occurs within a method, it creates an object. This object is called the exception object. It contains information about the exception, such as the name and description of the exception and the state of the program when the exception occurred.
Major reasons why an exception Occurs
- Invalid user input
- Device failure
- Loss of network connection
- Physical limitations (out of disk memory)
- Code errors
- Opening an unavailable file
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc. Errors are usually beyond the control of the programmer, and we should not try to handle errors.
Let us discuss the most important part which is the differences between Error and Exception that is as follows:
- Error: An Error indicates a serious problem that a reasonable application should not try to catch.
- Exception: Exception indicates conditions that a reasonable application might try to catch.
All exception and error types are subclasses of class Throwable, which is the base class of the hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch, Error is used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.
Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions.
Exceptions can be categorized in two ways:
- Built-in Exceptions
- Checked Exception
- Unchecked Exception
- User-Defined Exceptions
Let us discuss the above-defined listed exception that is as follows:
A. Built-in Exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations.
- Checked Exceptions: Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-time by the compiler.
- Unchecked Exceptions: The unchecked exceptions are just opposite to the checked exceptions. The compiler will not check these exceptions at compile time. In simple words, if a program throws an unchecked exception, and even if we didn’t handle or declare it, the program would not give a compilation error.
Note: For checked vs unchecked exception, see Checked vs Unchecked Exceptions
B. User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, users can also create exceptions, which are called ‘user-defined Exceptions’.
The advantages of Exception Handling in Java are as follows:
- Provision to Complete Program Execution
- Easy Identification of Program Code and Error-Handling Code
- Propagation of Errors
- Meaningful Error Reporting
- Identifying Error Types
Methods to print the Exception information:
1.printStackTrace()– This method prints exception information in the format of Name of the exception: description of the exception, stack
2.toString() – This method prints exception information in the format of Name of the exception: description of the exception.
3.getMessage() -This method prints only the description of the exception.
How Does JVM handle an Exception?
Default Exception Handling: Whenever inside a method, if an exception has occurred, the method creates an Object known as an Exception Object and hands it off to the run-time system(JVM). The exception object contains the name and description of the exception and the current state of the program where the exception has occurred. Creating the Exception Object and handling it in the run-time system is called throwing an Exception. There might be a list of the methods that had been called to get to the method where an exception occurred. This ordered list of the methods is called Call Stack. Now the following procedure will happen.
- The run-time system searches the call stack to find the method that contains a block of code that can handle the occurred exception. The block of the code is called an Exception handler.
- The run-time system starts searching from the method in which the exception occurred, and proceeds through the call stack in the reverse order in which methods were called.
- If it finds an appropriate handler, then it passes the occurred exception to it. An appropriate handler means the type of the exception object thrown matches the type of the exception object it can handle.
- If the run-time system searches all the methods on the call stack and couldn’t have found the appropriate handler, then the run-time system handover the Exception Object to the default exception handler, which is part of the run-time system. This handler prints the exception information in the following format and terminates the program abnormally.
Look at the below diagram to understand the flow of the call stack.
Let us see an example that illustrates how a run-time system searches for appropriate exception handling code on the call stack.
How Programmer Handles an Exception?
Customized Exception Handling: Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Briefly, here is how they work. Program statements that you think can raise exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch block) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed after a try block completes is put in a finally block.
Need for try-catch clause(Customized Exception Handling)
Consider the below program in order to get a better understanding of the try-catch clause.
Output explanation: In the above example, an array is defined with size i.e. you can access elements only from index 0 to 3. But you trying to access the elements at index 4(by mistake) that’s why it is throwing an exception. In this case, JVM terminates the program abnormally. The statement System.out.println(“Hi, I want to execute”); will never execute. To execute it, we must handle the exception using try-catch. Hence to continue the normal flow of the program, we need a try-catch clause.
How to Use the try-catch Clause?
Certain below key points are needed to be remembered that are as follows:
- In a method, there can be more than one statement that might throw an exception, So put all these statements within their own try block and provide a separate exception handler within their own catch block for each of them.
- If an exception occurs within the try block, that exception is handled by the exception handler associated with it. To associate the exception handler, we must put a catch block after it. There can be more than one exception handlers. Each catch block is an exception handler that handles the exception to the type indicated by its argument. The argument, ExceptionType declares the type of exception that it can handle and must be the name of the class that inherits from the Throwable class.
- For each try block, there can be zero or more catch blocks, but only one final block.
- The finally block is optional. It always gets executed whether an exception occurred in try block or not. If an exception occurs, then it will be executed after try and catch blocks. And if an exception does not occur, then it will be executed after the try block. The finally block in java is used to put important codes such as clean up code e.g., closing the file or closing the connection.
The summary is depicted via visual aid below as follows:
This article is contributed by Nitsdheerendra and Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java Programming Foundation – Self Paced Course
Find the right course for you to start learning Java Programming Foundation from the industry experts having years of experience. This Java Programming Foundation – Self Paced Course covers the fundamentals of the Java programming language, data types, operators and flow control, loops, strings, and much more. No more waiting! Start Learning JAVA Now and Become a Complete Java Engineer!
Exception Handling in Java | Example Program
Exception handling is the most valuable, important, and easy concept in whole Java.
It is also one of the most favorite topics of interviewer. Several questions can be asked based on this topic in Java tests and interviews.
In this tutorial, we will understand how to handle exception so that the program can continue to run else terminate gracefully.
Exception handling in java is a powerful mechanism or technique that allows us to handle runtime errors in a program so that the normal flow of the program can be maintained.
All the exceptions occur only at runtime. A syntax error occurs at compile time.
Let’s understand first the meaning of an exception in Java with realtime examples.
What is Exception in Java?
In general, an exception means a problem or an abnormal condition that stops a computer program from processing information in a normal way.
An exception in java is an object representing an error or an abnormal condition that occurs at runtime execution and interrupts (disrupts) the normal execution flow of the program.
In other words, unwanted and unexpected behavior/event that interrupts the normal execution flow of the program is called exception in java. It is thrown from a method. The caller of the method can catch and handle the exception.
An exception can be identified only at runtime, not at compile time. Therefore, it is also called runtime errors that are thrown as exceptions in Java. They occur while a program is running.
For example, if we access an array using an index that is out of bounds, we will get a runtime error named ArrayIndexOutOfBoundsException.
If we enter a double value while the program expecting an integer value, we will get a runtime error called InputMismatchException.
When JVM faces these kinds of errors or dividing an integer by zero in a program, it creates an exception object and throws it to inform us that an error has occurred.
If the exception object is not caught and handled properly, JVM will display an error message and will terminate the rest of the program abnormally.
If we want to continue the execution of remaining code in the program, we will have to handle exception object thrown by error condition and then display a user-friendly message for taking corrective actions. This task is known as exception handling in java.
Let’s understand it with some realtime examples.
Realtime Example of Exception in Java
1. Suppose you are watching a video on Youtube, suddenly, internet connectivity is disconnected or not working. In this case, you are not able to continue watching the video on Youtube. This interruption is nothing but an exception.
2. Suppose a person is traveling by car from Mumbai to Pune. After traveling mid-distance, the tire of his car is punctured. This unexpected or unwanted event is nothing but an exception.
The car owner always keeps an extra tire as an alternative on a long-distance journey. He changes the punctured tire with a new tire. After changing the tire, he continues the rest of the journey. This alternative way is called exception handling.
If this exception is not handled suitably, the rest of code in the program will not be executed. To handle runtime exception, we use the exceptional handling technique in java programming.
By handling the occurrence of exception, we can provide a meaningful message to the user about the error rather than a system-generated error message, which is difficult to understand for a user.
Let’s understand Java exception with a simple example program and see how an exception object is created and thrown.
Program code 1:
In the above program, when we enter 0 for the second number, a runtime error occurred because we cannot divide an integer by 0.
Why does Exception occur in Program?
There can be many reasons that might generate an exception in a Java program.
1. Opening a non-existing file in your program.
2. Reading a file from a disk, but the file does not exist there.
3. Writing data to a disk but the disk is full or unformatted.
4. When the program asks for user input and the user enters invalid data.
5. When a user attempts to divide an integer value by zero, an exception occurs.
6. When a data stream is in an invalid format, etc.
Exception Handling in Java
The mechanism of handling unexpected errors in a java program is called exception handling. It is a powerful mechanism to handle runtime errors, ClassNotFoundException, FileNotFoundException, IOException, etc. so that the normal execution flow of the program can be maintained.,
What is Exception Handler in Java?
The code that catches the exception thrown by JVM is called exception handler in Java. It is responsible for receiving information about the exception/error.
When an exception occurs, exception handling transfers the control of execution of the program to an appropriate exception handler.
For example, suppose we call a method that opens a file, but the file does not open. In this case, the execution of that method will stop and the code that we wrote to handle with this situation, will be run.
Therefore, we need an alternative way to tell JVM what code has to be executed to maintain the normal flow of the program when a certain exception occurs.
Thus, exception handling is an alternative way to continue the execution of the rest of the program normally.
How does Exception handling mechanism work?
The main purpose of using exception handling mechanism in a java program is to handle unexpected errors and maintain the normal flow of the program.
When an exceptional case occurs in a program, the exception handling mechanism performs the following tasks to manage unexpected situations in java program at runtime. The flow diagram can be seen in the below figure:
1. When an exception occurs inside a method in java program, the method in which exception has occurred, creates an exception object (i.e., an object of exception class) internally with the help of JVM and hands it over to the java runtime system (JVM). This process is called throwing an exception in java.
The exception object contains information about the exception such as the name of exception, and Stack Trace/Location.
2. When a java method throws an exception, JVM searches for a method in the method call stack that can handle that exception. A method call stack is an ordered list of methods. This process continues until the exception is caught by an exception handler.
The method which handles thrown exception is called exception handler. It is used to catch the exception that is thrown by JVM. This process is called catching an exception.
3. If an exception handler is found, the control of execution is transferred to exception handler, and statements specified inside exception handler are executed.
4. If JVM does not find an appropriate exception handler, exception is caught by the default exception handler provided by JVM.
Default exception handler is a part of the run-time system that displays exception information on the console such as exception name, message, and a full stack trace from where it was thrown.
The full stack track describes the sequence of steps that is responsible for throwing an error.
5. After printing exception information on the console, the default exception handler terminates the execution of the whole program abnormally.
Thus, an exception handler mechanism works to manage unexpected situations in a program at runtime. The exception may be user-defined (custom exception) or predefined. Most of the exceptions are predefined and must be handled in the program to avoid runtime errors.
You can keep in mind the working of exception handling mechanism by the below points.
- Get the exception (Detects problem)
- Throw exception (Inform that an error has occurred)
- Catch the exception (Receive error information)
- Handle exception (Take appropriate and corrective actions)
In Java program, we can handle such unexpected errors by using try and catch block.
Let’s take an example program to understand the concept of exception handling better.
Program code 2:
When you will run the above code, it will be successfully executed because there is no error in this program. Now, we will add one exceptional code to interrupt the normal flow of the program.
Program code 3:
When you will compile the above code, Java compiler will not show any kind of error and it will be successfully compiled but at runtime, an Arithmetic exception will be thrown by JVM. Let’s understand how it happened?
In the preceding code, exception has occurred in the main() method, therefore, main method will create an exception object of ArithmeticException class and hands it over to java run-time system.
Now, JVM will check inside the main method, error handling code is there or not. Since the main method did not handle exception, JVM will terminate main method abnormally and hands over to the default exception handler.
The default exception handler will catch the exception thrown by JVM and display a system-generated error message on the console.
After displaying a system-generated error message, the default exception handler will terminate the entire program. Let’s compile the above code and look at the output.
As we can observe in the output of above code, we did not get the output as expected because an ArithmeticException exception is generated when a value is divided by zero, which is illegal.
This exception terminated the program execution and did not execute the rest of the statement, and shown a system-generated error message to the user.
This system generated error message is not user-friendly and a user will not be able to understand what went wrong. So, to give a user-friendly message to the client and for taking corrective actions, we handle exceptions in the program.
A programmer can handle this exception easily and then print a user-friendly warning message to the user, which helps them to correct the error as most of the time exception occurs in coding. Let’s see how?
Program code 4:
Now, notice that we handled exception in catch block thrown by try block in the program and printed a user-friendly message on the console.
ArithmeticException is a class that is used to handle all arithmetical exceptions. It extends RuntimeException.
Thus, we can handle exception occurring at runtime and can maintain the normal flow of the program. We will learn try-catch block in more detail in the further tutorial.
Java Default Exception Handling Example Program
Let’s take an example program to understand the concepts of java method call stack.
Program code 5:
In the above code, there is only the main thread. For every thread, JVM creates one runtime stack. The main() method is called by JVM. For every method call, JVM will add one entry in the method call stack as shown in the following figure.
Method call stack is the chain/order of methods that our program will execute to get to the current method. We represent method call stack as growing upward. The method that is to be called first, will go at the bottom.
The method that will be called at last, will go at the top of the stack. If we move back down in the call stack, we are moving the current method to previously called method. Now, look at the above figure that will show how the call stack in java works.
Now, the main() method is calling m1(). So, JVM will add one entry for m1() method in the call stack. The control of execution is transferred to the m1() method.
Similarly, the m1() method is calling the m2() method. Again, JVM will add one entry for m2() method in the method call stack. The control of execution will be transferred to m2() method.
The method m2() is calling m3() method. JVM will add one entry for m3() method as shown in the above figure and the control of execution will be transferred to method m3().
Inside the m3() method, an exception has occurred, so the m3() method will create an exception object internally and hands over it to JVM. Now, JVM checks the exception handling code is there or not.
Since inside the m3() method, there is no error handling code, so JVM immediately, terminates this method abnormally without execution of its remaining code and removed the corresponding entry from the method call stack.
Now JVM will search that method which is calling m3(). Since m3() method is called by m2(). So, the control of execution will go back to m2() method and JVM will again check that m2() is handled the exception or not.
Since m2 is not handled the exception there, JVM terminates m2() method abnormally and removed the corresponding entry from the call stack.
Similarly, JVM will again search that method that is calling m2(). The method m2() is called by m1(). The control of execution will go back to m1() method and JVM will check that exception handling is there or not.
Since m1() is not handled the exception, JVM terminates m1() abnormally and removed the corresponding entry from the call stack.
Since m1() is called by main() method but the main() method did not handle the exception. So, JVM will terminate the main() method abnormally and will remove the corresponding entry from the call stack.
At last, JVM is responsible to handle this exception because JVM called the main method to start the execution of program. JVM will hand over exception to the default exception handler.
The default exception handler will just print exception information on the console and terminates the whole program abnormally. Thus, the method call stack works in java.
Now observe the name of exception, description, and stack trace in the below output.
Let’s modify something in the above program.
Program code 6:
In this program, there is only one thread called main thread. JVM calls the main method to start the execution of program. Now, JVM will add one entry for main method in the runtime call stack as shown in the figure.
The main method is calling m1() method. So, JVM will add one entry for m1() method in the call stack. The control of execution goes to m1() method. Inside the m1() method, m2() method is calling, JVM will add one entry for m2() method in call stack.
The control goes to m2() method and prints “Hello” on the console. After the complete execution of m2() method normally, JVM will remove the corresponding entry from call stack as shown in figure.
Now, the control goes back to the inside m1() method for execution of next statement. On the execution of next statement inside m1() method, an exception occurs. So, the m1() method will create an exception object and hands over it to the runtime system (JVM).
Now, JVM will check that this m1() method is having exception handling code or not. Since there is not handling code inside the m1(), JVM will terminate it abnormally and the corresponding entry will be removed from the call stack.
JVM will identify which method is calling m1() method? Since main method is calling m1. Therefore, the control goes back to the main method but there is also no error handling code inside main method.
So, JVM will terminate main method abnormally and remove the corresponding entry from the call stack.
At last, JVM is the caller of main method. Therefore, JVM is responsible to handle this exception. It will hand over the exception to default exception handler.
The default exception handler will just print exception information on the console and terminates the entire program abnormally.
Now observe the output of the program.
Advantage of Exception Handling
There are several advantages of using exception handling in java. They are as follows:
1. The main advantage of exception handling technique is to maintain the normal flow of the program.
2. It provides flexibility in handling situations of errors.
3. It allows us to define a user-friendly message to handle the exception.
4. The exception handling technique helps to separate “Error-Handling code” from “Regular code.”
Hope that this tutorial has covered almost all the basic important points related to exception handling mechanism/technique in java with realtime examples and programs.
I hope you will have understood this topic and enjoyed it. In the next tutorial, we will learn exception hierarchy in java.
Thanks for reading. Next ⇒ Exception Hierarchy in Java ⇐ PrevNext ⇒