Exception Handling in Java

 

🔷 Introduction to Exception Handling in Java

Exception Handling in Java is a powerful mechanism that allows a program to detect and respond to run-time errors (exceptions) gracefully, without crashing the program.

Exceptions are unexpected events that disrupt the normal flow of a program, such as:

  • Division by zero

  • File not found

  • Null pointer access

  • Array index out of bounds


✅ Why Exception Handling?

  • To handle errors effectively and maintain normal application flow.

  • To separate error-handling code from regular code.

  • To provide meaningful error messages to users.

  • To prevent program termination due to runtime errors.


✅ Exception Handling Keywords

KeywordDescription
tryDefines a block of code to monitor for exceptions
catchDefines a block to handle the exception
finallyBlock that always executes, used for cleanup code
throwUsed to explicitly throw an exception
throwsDeclares the exceptions a method might throw

🔁 Basic Example


public class Example { public static void main(String[] args) { try { int result = 10 / 0; // Will cause ArithmeticException } catch (ArithmeticException e) { System.out.println("Cannot divide by zero!"); } finally { System.out.println("This always runs."); } } }

✅ Types of Exceptions

1. Checked Exceptions

  • These are exceptions that are checked at compile-time.

  • The compiler ensures that the programmer handles them.

  • Must be caught using try-catch or declared using throws.

Examples:

  • IOException

  • SQLException

  • ClassNotFoundException


import java.io.*; public class CheckedExample { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new FileReader("file.txt")); System.out.println(reader.readLine()); } }

2. Unchecked Exceptions

  • These occur at runtime and are not checked at compile-time.

  • Caused by programming errors, and optional to handle.

Examples:

  • ArithmeticException

  • NullPointerException

  • ArrayIndexOutOfBoundsException


public class UncheckedExample { public static void main(String[] args) { int[] arr = {1, 2, 3}; System.out.println(arr[5]); // ArrayIndexOutOfBoundsException } }

✅ Exception Class Hierarchy


java.lang.Object └── java.lang.Throwable ├── java.lang.Error (serious problems, not handled) └── java.lang.Exception ├── Checked Exceptions (IOException, SQLException, etc.) └── Unchecked Exceptions (RuntimeException and its subclasses)

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Inheritance and Polymorphism