J
Exception Handling
Java syntax guide
Error handling with try-catch blocks in Java
Exception Handling
Error handling with try-catch blocks in Java
Java exception handling (java)
import java.io.*;
import java.util.Scanner;
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
// Multiple operations that might throw exceptions
readFile("example.txt");
divideNumbers(10, 0);
processArray(null);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("Math error: " + e.getMessage());
} catch (NullPointerException e) {
System.out.println("Null pointer: " + e.getMessage());
} catch (Exception e) {
// Catch-all for unexpected exceptions
System.out.println("Unexpected error: " + e.getMessage());
} finally {
// Always executed
System.out.println("Cleanup completed");
}
// Try-with-resources (Java 7+)
try (Scanner scanner = new Scanner(System.in);
FileWriter writer = new FileWriter("output.txt")) {
System.out.print("Enter your name: ");
String name = scanner.nextLine();
writer.write("Hello, " + name + "!");
} catch (IOException e) {
System.out.println("IO Error: " + e.getMessage());
}
}
// Method that throws checked exception
public static void readFile(String filename) throws FileNotFoundException {
File file = new File(filename);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
// Method that throws unchecked exception
public static int divideNumbers(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
return a / b;
}
// Method that might throw NullPointerException
public static void processArray(String[] array) {
if (array == null) {
throw new NullPointerException("Array cannot be null");
}
System.out.println("Array length: " + array.length);
}
}
// Custom exception class
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
class PersonValidator {
public static void validateAge(int age) throws InvalidAgeException {
if (age < 0) {
throw new InvalidAgeException("Age cannot be negative");
}
if (age > 150) {
throw new InvalidAgeException("Age seems unrealistic");
}
}
public static void main(String[] args) {
try {
validateAge(-5);
} catch (InvalidAgeException e) {
System.out.println("Validation error: " + e.getMessage());
}
}
}
Explanation
Java uses try-catch-finally blocks to handle exceptions, which are events that disrupt the normal flow of a program. This allows for graceful error recovery.
Common Use Cases
- Preventing program crashes
- Handling file I/O errors
- Managing network communication issues
- Validating user input
Related Java Syntax
Master Exception Handling in Java
Understanding exception handling is fundamental to writing clean and efficient Java code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.
Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using exception handling effectively in your Java projects.
Key Takeaways
- Preventing program crashes
- Handling file I/O errors
- Managing network communication issues