Lesson 53
Exception Handling
Exception handling in Java detects, catches, and handles runtime errors using try, catch, finally, throw, and throws to maintain normal program flow.
Java Track
Save progress as you learn.
61 lessons
Lesson content
Exception handling in Java is a mechanism used to handle runtime errors and prevent abnormal program termination. It helps maintain the normal flow of a program by detecting errors, catching exceptions, and taking appropriate corrective actions.
Definition List
- Exception: An event that occurs during program execution and disrupts the normal flow of instructions.
- Exception Handling: A mechanism used to detect, catch, and handle runtime errors.
- try Block: Contains code that may generate an exception.
- catch Block: Handles the exception thrown by the try block.
- finally Block: Executes regardless of whether an exception occurs or not.
- Throwable: The root class of Java's exception hierarchy.
Exception Handling Syntax
try {
// statement that causes an error
} catch (Exception_type e) {
// statement to handle the error
}Example 01: ArithmeticException
class ExceptionDemo {
public static void main(String arg[]) {
int a = 10;
int b = 5;
int c = 5;
int x;
try {
x = a / (b - c);
} catch (ArithmeticException e) {
System.out.println("Division by zero error");
}
}
}Output
Division by zero errorExample 02: ArrayIndexOutOfBoundsException
package Execption_Handling;
public class ArrayIndexOutOfBoundsExample {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5}; // Array of size 5
try {
System.out.println("Element at index 2: " + arr[2]); // Valid index
System.out.println("Element at index 5: " + arr[5]); // Invalid index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
}
try {
System.out.println("Element at index -1: " + arr[-1]); // Invalid negative index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
}
}
}Example 03: IOException
package Execption_Handling;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class IOExceptionExample {
public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("testfile.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An I/O error occurred: " + e.getMessage());
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
System.out.println("Failed to close the reader: " + e.getMessage());
}
}
}
}Example 04: NumberFormatException
package Execption_Handling;
public class NumberFormatExceptionExample {
public static void main(String[] args) {
String validNumber = "123";
String invalidNumber = "123abc";
String emptyString = "";
String nullString = null;
try {
int num = Integer.parseInt(validNumber);
System.out.println("Parsed number: " + num);
num = Integer.parseInt(invalidNumber); // throws NumberFormatException
System.out.println("Parsed number: " + num);
} catch (NumberFormatException e) {
System.out.println("Invalid number format: " + e.getMessage());
}
try {
int num = Integer.parseInt(emptyString);
System.out.println("Parsed number: " + num);
} catch (NumberFormatException e) {
System.out.println("Invalid number format (empty string): " + e.getMessage());
}
try {
int num = Integer.parseInt(nullString);
System.out.println("Parsed number: " + num);
} catch (NumberFormatException e) {
System.out.println("Invalid number format (null string): " + e.getMessage());
}
}
}Exception Handling Keywords
// try — contains code that may throw an exception
try { /* risky code */ }
// catch — handles the exception
catch (Exception e) { /* handle exception */ }
// finally — executes whether or not an exception occurs
finally { /* cleanup code */ }
// throw — explicitly throws an exception
throw new ArithmeticException();
// throws — declares exceptions a method may throw
public void readFile() throws IOExceptionBest Practices
- Catch specific exceptions — avoid catching generic exceptions whenever possible.
- Use finally for cleanup to ensure resources such as files and streams are released properly.
- Provide meaningful error messages to help users and developers understand the problem.
- Avoid empty catch blocks — always handle exceptions appropriately.
- Use exception handling for exceptional situations, not as a substitute for normal program logic.
FAQ
1. What is exception handling in Java?
Exception handling is a mechanism used to detect, catch, and handle runtime errors so that the program can continue executing normally.
2. What is the difference between try and catch in Java?
The try block contains code that may generate an exception, while the catch block handles the exception when it occurs.
3. What are the most common exceptions in Java?
Some common Java exceptions include ArithmeticException, ArrayIndexOutOfBoundsException, IOException, NumberFormatException, and FileNotFoundException.
Where Java is used
Java in real-world development
try
Wraps code that may throw an exception. If an exception occurs, control transfers immediately to the matching catch block.
catch
Receives and handles the exception thrown by the try block. Matched by exception type.
finally
Executes after try/catch regardless of outcome. Used to close files, streams, or database connections.
throw
Explicitly throws an exception object from within a method or block.
throws
Declared in a method signature to indicate which checked exceptions the method may propagate to its caller.
ArithmeticException
Thrown when an illegal arithmetic operation occurs, such as dividing an integer by zero.