0% found this document useful (0 votes)
3 views

Module-4

Uploaded by

subhani.shaik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Module-4

Uploaded by

subhani.shaik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Module-4

Exception Handling
Exceptions in Java
In Java, exceptions are events that disrupt the normal flow of a program during execution.
They are objects that represent an error or unexpected condition.
Why Use Exceptions?
 To handle runtime errors gracefully
 To maintain the flow of execution
 To separate error-handling code from regular code

Types of Exceptions

Java exceptions are divided into two main categories:

1. Checked Exceptions

 Handled during compile time


 Must be either caught or declared
 Examples:

try {

FileReader file = new FileReader("file.txt");

} catch (IOException e) {

System.out.println("File not found!");

2. Unchecked Exceptions

 Handled during runtime


 Inherit from RuntimeException
 Not mandatory to catch or declare
 Examples:

Syntax

int a = 5 / 0; // Throws ArithmeticException

Exception Hierarchy
java.lang.Object
└── java.lang.Throwable
├── java.lang.Error
└── java.lang.Exception
├── Checked Exceptions
└── RuntimeException (Unchecked)
Common Exception Handling Keywords
Example: Try-Catch-Finally
public class Example {
public static void main(String[] args) {
try {
int[] arr = new int[3];
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index is out of bounds!");
} finally {
System.out.println("This always executes.");
}
}
}
Multiple Catch Clauses in Java
In Java, a try block can be followed by multiple catch blocks to handle different types of
exceptions separately.
Why Use Multiple Catch Blocks?
 To handle different exceptions differently
 To maintain clean and readable error-handling logic
 To catch specific exceptions before general ones
try {
// Code that may throw multiple exceptions
} catch (ArithmeticException e) {
System.out.println("Arithmetic error occurred.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is invalid.");
} catch (Exception e) {
System.out.println("Some other exception occurred.");
}
Example: Handling Multiple Exceptions
public class MultiCatchExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
int result = 10 / 0; // ArithmeticException
System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Arithmetic error: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index error: " + e.getMessage());
} catch (Exception e) {
System.out.println("General error: " + e.getMessage());
}
}
}
Nested try Statement in Java
In Java, a nested try block means using a try block inside another try block. It allows for more
granular exception handling, especially when different pieces of code might throw different
exceptions.
Why Use Nested try Blocks?
 To handle independent errors separately within the same scope
 To catch specific exceptions where they occur
 To prevent one exception from skipping the rest of the code
Syntax:
try {
// Outer try block
try {
// Inner try block
} catch (ExceptionType1 e1) {
// Inner catch block
}
} catch (ExceptionType2 e2) {
// Outer catch block
}
Example: Nested Try-Catch
public class NestedTryExample {
public static void main(String[] args) {
try {
// Outer try block
int[] arr = new int[3];

try {
// Inner try block
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Inner catch: Cannot divide by zero.");
}
System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Outer catch: Array index out of bounds.");
}
System.out.println("Program continues...");
}
}
Output
Inner catch: Cannot divide by zero.
Outer catch: Array index out of bounds.
Program continues...
throw vs throws vs finally in Java
throw Keyword
Used to explicitly throw a single exception object (either built-in or custom).
Syntax:
throw new ExceptionType("error message");
Example:
public class ThrowExample {
public static void main(String[] args) {
int age = 15;
if (age < 18) {
throw new ArithmeticException("Access Denied - You must be 18+");
}
System.out.println("Access Granted!");
}
}
throws Keyword
Used in method declarations to indicate that the method might throw an exception.
Syntax:
returnType methodName() throws ExceptionType {
// code
}
Example:
import java.io.*;

public class ThrowsExample {


public static void readFile() throws IOException {
FileReader fr = new FileReader("test.txt"); // might throw IOException
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
}
}
}
finally Block
A finally block is always executed, whether or not an exception is thrown or caught. Used to
clean up resources like closing files, releasing connections, etc.
Syntax:
try {
// risky code
} catch (Exception e) {
// handle exception
} finally {
// cleanup code
}
Example:
public class FinallyExample {
public static void main(String[] args) {
try {
int a = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("Finally block executed.");
}
}
}
Built-in Exceptions
Java provides a rich set of built-in exceptions to handle common error scenarios. These are
part of the Java Exception Hierarchy, and most of them are subclasses of the Exception or
RuntimeException classes.

Examples of Built-in Exceptions


➤ ArithmeticException
int result = 10 / 0; // Throws ArithmeticException
➤ NullPointerException
String str = null;
System.out.println(str.length()); // Throws NullPointerException
➤ ArrayIndexOutOfBoundsException
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // Throws ArrayIndexOutOfBoundsException
➤ FileNotFoundException
FileReader fr = new FileReader("file.txt"); // Must be handled or declared

User-Defined Exceptions in Java


In Java, you can create your own custom exceptions (user-defined exceptions) to handle
specific application-level errors that the built-in exceptions don’t cover.

Why Use User-Defined Exceptions?


 To represent application-specific errors (e.g., InvalidAgeException,
InsufficientBalanceException).
 To make error handling more meaningful and readable.
 To extend existing exception functionality with custom messages or logic.

Creating a User-Defined Exception


User-defined exceptions are created by extending:
 Exception class → for checked exceptions
 RuntimeException class → for unchecked exceptions
Example: Checked Custom Exception
// Step 1: Define the custom exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
// Step 2: Use it in your program
public class Test {
static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above.");
} else {
System.out.println("You are eligible to vote.");
}
}
public static void main(String[] args) {
try {
checkAge(15);
} catch (InvalidAgeException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

You might also like