Exception Handling
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.
Exception can be categorized in two ways:
1. Built-in Exceptions
i) Checked Exception
ii) Unchecked Exception
2. User-Defined Exception
1. Built-In Exception:
Built-in Exception are pre-defined exception classes provided by Java to handle common
errors during program execution.
i) Checked Exception:
Checked Exceptions are called compile-time exceptions because these exceptions are
checked at compile-time by compiler.
Examples of Checked Exception are:
• ClassNotFoundException
• InterruptedException
• IOException
• FileNotFoundException
ii) Unchecked Exception:
The unchecked exceptions are just opposite to the checked exception. The compiler will not
check these exceptions at compile time.
Examples:
• ArithmeticException
• ArrayIndexOutOfBoundException
• ArrayStoreException
• NullPointerException
2. User-Defined Exception:
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".
Handling division by zero:
public class ExceptionExample {
public static void main(String[] args) {
int a = 10;
int b = 0;
try {
int result = a / b;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: can't divide by 0");
}
System.out.println("After Exception handling");
}
}
Output:
Error: can't divide by zero.
After Exception handling.
The above program demonstrates exception handling using division. It attempts to divide
10 by 0, which causes an ArithmeticException. The try block holds the risky code, and the
catch block handles the error. Instead of crashing, the program prints an error message. It
then continues normal execution after handling the exception.
Advantages of Exception Handling:
• Provision to complete program execution.
• Easy identification of program code and error-handling code.
• Propagation of errors.
• Meaningful error reporting.
• Identifying error types.