0% found this document useful (0 votes)
3 views10 pages

Exception Handling in Java

The document provides an overview of exception handling in Java, detailing its importance in maintaining normal application flow during runtime errors. It explains the structure of try, catch, and finally blocks, as well as the JVM's reaction to exceptions, including detection, creation of exception objects, and handling. Additionally, it categorizes exceptions into checked and unchecked types, illustrating their differences and providing examples for each.
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 views10 pages

Exception Handling in Java

The document provides an overview of exception handling in Java, detailing its importance in maintaining normal application flow during runtime errors. It explains the structure of try, catch, and finally blocks, as well as the JVM's reaction to exceptions, including detection, creation of exception objects, and handling. Additionally, it categorizes exceptions into checked and unchecked types, illustrating their differences and providing examples for each.
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/ 10

Exception Handling in Java

The exception handling in java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO,


SQL, Remote etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the
application. Exception normally disrupts the normal flow of the application that is why
we use exception handling. Let's take a scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

Suppose there is 10 statements in your program and there occurs an exception at


statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If
we perform exception handling, rest of the exception will be executed. That is why we
use exception handling in java.

Hierarchy of Exception classes

Control Flow in Exception Handling refers to the order in which the program executes code
in the presence of exceptions (errors). It defines how the program behaves when an exception
occurs and how it shifts the flow of control from normal execution to the exception-handling
blocks.

🔄 Normal Control Flow vs Exception Control Flow

✅ Normal Flow:

 The program executes statements sequentially, from top to bottom.

❌ Exception Flow:

 If an exception occurs, the normal flow is interrupted, and control jumps to the
exception handling block (catch or finally).
🔧 Control Flow in Java Exception Handling

Java uses try, catch, and finally blocks for exception handling.

try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code that handles the exception
} finally {
// Code that always runs (cleanup code)
}

📊 Control Flow Steps:

1. try Block Starts:


o Code runs normally until an exception occurs.
2. If No Exception:
o catch is skipped.
o finally (if present) is executed.
o Control moves after finally.
3. If Exception Occurs:
o The remaining code in try is skipped.
o Control jumps to the matching catch block.
o Then finally is executed (if present).
o Control resumes after finally.

🧠 Example:
public class Example {
public static void main(String[] args) {
try {
int a = 10 / 0; // ArithmeticException
System.out.println("This won't be printed.");
} catch (ArithmeticException e) {
System.out.println("Caught an exception: " + e);
} finally {
System.out.println("Finally block executed.");
}
System.out.println("Program continues...");
}
}

Output:

Caught an exception: java.lang.ArithmeticException: / by zero


Finally block executed.
Program continues...
🔁 Summary of Control Flow:
Scenario try catch finally After blocks

No Exception Executed Skipped Executed Continues

Exception Occurs Stops at exception Matching catch runs Executed Continues

JVM Reaction to Exception – Explained

When an exception occurs during the execution of a Java program, the Java Virtual
Machine (JVM) reacts in a specific way to handle the abnormal situation. Here's a step-by-
step explanation of how the JVM reacts to an exception:

1. Detection of Exception

When the JVM encounters an error condition (like divide by zero, null reference, invalid
array index, etc.), it detects the exception and creates an exception object.

Example:

int a = 5 / 0; // ArithmeticException is detected by JVM

2. Creating Exception Object

Once detected, the JVM creates an object of the exception class (which extends Throwable).
This object contains:

 Name and type of exception


 Description of the error
 Stack trace (method call hierarchy where the exception occurred)

3. Searching for Exception Handler

The JVM starts searching for a matching catch block (exception handler) in the current
method using a mechanism called stack unwinding:

 It checks if the current method has a try-catch block that can handle the exception.
 If not found, it moves to the caller method (previous method in the call stack), and so
on.

4. Handling or Terminating

There are two possible outcomes:


a. Handled Exception:

If a matching catch block is found, the JVM passes the exception object to it and the
program continues executing from there.

Example:

try {
int a = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Division by zero is not allowed.");
}

b. Unhandled Exception:

If no catch block is found in the entire call stack:

 JVM terminates the program abnormally.


 It prints the stack trace to the console showing where the exception occurred.

What is a try Block? – Explained Briefly

The try block in Java is used to write code that might cause an exception during runtime.

✅ Purpose:

It allows you to test a block of code for errors without crashing the program.

✅ Key Points:

 It must be followed by either a catch block or a finally block.


 If an exception occurs, Java jumps to the catch block (if present).
 If no exception occurs, the code inside the try block runs normally.

🔸 Syntax:
try {
// Code that might throw an exception
}

🔸 Example:
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}

In the above example:

 The try block contains risky code.


 If an exception occurs, control goes to the catch block.

Purpose of the try Block

The try block is designed to test a section of code for errors. If an error occurs within this
block, the program control is transferred to the corresponding except (in Python) or catch
(in Java, JavaScript, etc.) block, where the error can be handled appropriately. This approach
prevents abrupt termination of the program and allows for error logging, user notifications, or
alternative actions.

Syntax.

try {

// Code that might throw an exception

riskyOperation();

} catch (Exception e) {

// Handle the exception

System.out.println("An error occurred: " + e.getMessage());

Purpose of the catch Block

 Error Handling: Intercepts exceptions thrown in the try block.


 Program Stability: Prevents abrupt termination by managing exceptions.
 Custom Responses: Allows developers to define specific actions in response to
different exceptions.

try {

// Code that may throw an exception

} catch (ExceptionType e) {

// Code to handle the exception

Example

public class CatchExample {

public static void main(String[] args) {

try {
int result = 10 / 0; // This will throw ArithmeticException

} catch (ArithmeticException e) {

System.out.println("Cannot divide by zero!");

Purpose of the finally Block

In Java, the finally block is a crucial component of exception handling. It is used to execute
important code such as resource cleanup, regardless of whether an exception is thrown or caught.
The finally block always executes when the try block exits, ensuring that cleanup code runs even
if an unexpected exception occurs.

Syntax

try {

// Code that may throw an exception

} catch (ExceptionType e) {

// Code to handle the exception

} finally {

// Code that will always execute

Example

public class FinallyExample {

public static void main(String[] args) {

try {

int data = 50 / 0; // This will throw ArithmeticException

} catch (ArithmeticException e) {

System.out.println("Exception caught: " + e);

} finally {
System.out.println("Finally block is always executed");

Purpose of the throw Keyword

 Explicit Exception Throwing: throw is used to manually trigger an exception, often


based on specific conditions or validations.
 Custom Error Handling: It facilitates the creation of custom exceptions, allowing
developers to define and handle application-specific error scenarios.
 Control Flow Management: By throwing exceptions, developers can alter the
normal flow of execution, directing it to appropriate catch blocks or terminating the
program gracefully.

🔹 Syntax
throw new ExceptionType("Error message");

 ExceptionType must be a subclass of Throwable, such as Exception or


RuntimeException.
 The throw statement is typically used within methods or blocks of code to indicate
that an exceptional condition has occurred.

🔹 Example: Throwing a Built-in Exception


public class ThrowExample {
public static void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older.");
}
System.out.println("Age is valid.");
}

public static void main(String[] args) {


validateAge(16);
}
}

Purpose of the throws Keyword


In Java, the throws keyword is used in method declarations to indicate that a method might throw
one or more exceptions during its execution. This mechanism allows a method to delegate the
responsibility of handling certain exceptions to its caller, promoting cleaner code and centralized
exception management.

Syntax

returnType methodName(parameters) throws ExceptionType1, ExceptionType2, ... {

// method body

Example

import java.io.*;

public class FileReaderExample {

// Method that declares it might throw an IOException

public static void readFile(String fileName) throws IOException {

BufferedReader reader = new BufferedReader(new FileReader(fileName));

System.out.println(reader.readLine());

reader.close();

public static void main(String[] args) {

try {

readFile("example.txt");

} catch (IOException e) {

System.out.println("An error occurred: " + e.getMessage());

Types of Exception
In Java, exceptions are events that disrupt the normal flow of a program's execution. They are
categorized into three main types: Checked Exceptions, Unchecked Exceptions, and Errors.

Checked Exceptions

 Definition: Exceptions that are checked at compile-time. The compiler ensures that
these exceptions are either caught using a try-catch block or declared in the method
signature using the throws keyword.
 Purpose: They represent conditions that a program should anticipate and recover
from, such as issues related to file I/O or database access.GeeksforGeeks+1Rollbar+1
 Examples:
o IOException
o SQLException
o ClassNotFoundException
o FileNotFoundExceptionGeeksforGeeks+1raygun.com+1Stackify
 Usage Example:

import java.io.*;

public class CheckedExample {

public static void readFile(String fileName) throws IOException {

BufferedReader reader = new BufferedReader(new FileReader(fileName));

System.out.println(reader.readLine());

reader.close();

public static void main(String[] args) {

try {

readFile("example.txt");

} catch (IOException e) {

System.out.println("An error occurred: " + e.getMessage());

}
Unchecked Exceptions

 Definition: Exceptions that are not checked at compile-time. The compiler does not
require methods to handle or declare them.
 Purpose: They usually indicate programming errors, such as logic mistakes or
improper use of APIs.
 Examples:
o NullPointerException
o ArrayIndexOutOfBoundsException
o ArithmeticException
o IllegalArgumentException

Example

public class UncheckedExample {

public static void main(String[] args) {

int[] numbers = {1, 2, 3};

System.out.println(numbers[5]); // Throws ArrayIndexOutOfBoundsException

You might also like