



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




Java Exception Handling Last Updated : 27 Aug, 2025 Exception handling in Java is an effective mechanism for managing runtime errors to ensure the application's regular flow is maintained. Some Common examples of exceptions include ClassNotFoundException, IOException, SQLException, RemoteException, etc. By handling these exceptions, Java enables developers to create robust and fault-tolerant applications. Example: Showing an arithmetic exception or we can say a divide by zero exception. import java.io.*; class Geeks { public static void main(String[] args) { int n = 10; int m = 0; int ans = n / m; System.out.println("Answer: " + ans); } }
Output: output Note: When an exception occurs and is not handled, the program terminates abruptly and the code after it, will never execute. Example : The below Java program modifies the previous example to handle an ArithmeticException using try-catch and finally blocks and keeps the program running. import java.io.*; class Geeks { public static void main(String[] args) { int n = 10; int m = 0; try { // Code that may throw an exception int ans = n / m; System.out.println("Answer: " + ans); } catch (ArithmeticException e) { // Handling the exception
Heirarchy of exception Major Reasons Why an Exception Occurs Exceptions can occur due to several reasons, such as: Invalid user input Device failure Loss of network connection Physical limitations (out-of-disk memory) Code errors Out of bound Null reference Type mismatch Opening an unavailable file Database errors
Arithmetic errors Errors are usually beyond the control of the programmer and we should not try to handle errors. Types of Java Exceptions Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their it's exceptions.
Exceptions can be categorized in two ways:
A try-catch block in Java is a mechanism to handle exception. The try block contains code that might thrown an exception and the catch block is used to handle the exceptions if it occurs. Internal working of try-catch Block Java Virtual Machine starts executing the code inside the try block. If an exception occurs, the remaining code in the try block is skipped and the JVM starts looking for the matching catch block. If a matching catch block is found, the code in that block is executed. After the catch block, control moves to the finally block (if present). If no matching catch block is found the exception is passed to the JVM default exception handler. The final block is executed after the try catch block. regardless of whether an exception occurs or not. try { // Code that may throw an exception } catch (ExceptionType e) { // Code to handle the exception }