0% found this document useful (0 votes)
2 views16 pages

Exception Handling.java

An Exception is a runtime error that interrupts the normal flow of a program, and exception handling is necessary to prevent program crashes and improve user experience. Java exceptions are categorized into checked exceptions, which must be handled at compile time, and unchecked exceptions, which occur at runtime. The document explains the use of try, catch, and finally blocks for handling exceptions, as well as the throw and throws keywords for managing exceptions in methods.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

Exception Handling.java

An Exception is a runtime error that interrupts the normal flow of a program, and exception handling is necessary to prevent program crashes and improve user experience. Java exceptions are categorized into checked exceptions, which must be handled at compile time, and unchecked exceptions, which occur at runtime. The document explains the use of try, catch, and finally blocks for handling exceptions, as well as the throw and throws keywords for managing exceptions in methods.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

What is an Exception?

An Exception is an event that occurs during the execution of a program that interrupts the normal
flow of the program.

In simple words,

An exception is a runtime error that Java can detect and handle.

Example:

int a = 10;
int b = 0;

[Link](a / b);

Output

Exception in thread "main" [Link]: / by zero

The program crashes because division by zero is not allowed.

Why Exception Handling is Needed?

Without exception handling:

• Program terminates immediately

• Remaining code is never executed

• Bad user experience

• Difficult to debug

Example

public class Demo {

public static void main(String[] args) {

[Link]("Program Started");

int result = 10 / 0;

[Link](result);

[Link]("Program Ended");
}

}
Output

Program Started

Exception in thread "main" [Link]

Notice

Program Ended

never executes.

With exception handling

public class Demo {

public static void main(String[] args) {

[Link]("Program Started");

try {

int result = 10 / 0;
[Link](result);

} catch (ArithmeticException e) {

[Link]("Cannot divide by zero");

[Link]("Program Ended");

Output

Program Started
Cannot divide by zero
Program Ended

The program continues running.

Types of Exceptions

Java exceptions are mainly divided into two categories.

[Link] Exceptions

[Link] Exceptions
1. Checked Exceptions

These exceptions are checked by the compiler.

If you don't handle them, your program will not compile.

Examples

• IOException

• FileNotFoundException

• SQLException

• ClassNotFoundException

Example

import [Link];

public class Demo {

public static void main(String[] args) {

FileReader file = new FileReader("[Link]");

Compile Error

Because Java forces you to handle this exception.

Correct way

import [Link].*;

public class Demo {

public static void main(String[] args) {

try {

FileReader file = new FileReader("[Link]");

} catch (FileNotFoundException e) {

[Link]("File not found");

}
}

2. Unchecked Exceptions

These are not checked by the compiler.

They occur during runtime.

Examples

• ArithmeticException

• NullPointerException

• ArrayIndexOutOfBoundsException

• NumberFormatException

Example

int arr[] = {10,20,30};

[Link](arr[5]);

Output

ArrayIndexOutOfBoundsException

Difference Between Checked and Unchecked Exceptions

Checked Exception Unchecked Exception

Checked by compiler Not checked by compiler

Must handle Optional to handle

Happens before runtime Happens during runtime

Compiler gives error Program compiles successfully

Example: IOException Example: ArithmeticException


try Block

The try block contains the code that may generate an exception.

Syntax

try {

// risky code

Example

try {

int result = 10 / 0;

catch Block

The catch block handles the exception.

Syntax

try {

}
catch(ExceptionType e){

Example

try {

int result = 10 / 0;

}
catch(ArithmeticException e){

[Link]("Division by zero is not allowed");

Output

Division by zero is not allowed


How try and catch Work

Flow

Program Starts
|
|
try Block Executes
|
Exception?
/ \
No Yes
| |
Continue Jump to catch
|
Continue Program

finally Block

The finally block always executes, whether an exception occurs or not.

It is mainly used for

• Closing files

• Closing database connections

• Cleaning resources

Syntax

try{

}
catch(Exception e){

}
finally{

Example
public class Demo {

public static void main(String[] args) {

try {

int result = 10 / 0;

catch (ArithmeticException e) {

[Link]("Handled");

finally {

[Link]("Finally block executed");

Output

Handled
Finally block executed

Even without exception

try {

[Link]("Hello");

finally {

[Link]("Finally");

Output

Hello
Finally
throw Keyword

The throw keyword is used to manually create an exception.

Syntax

throw new ExceptionType();

Example

public class Demo {

public static void main(String[] args) {

int age = 15;

if(age < 18){

throw new ArithmeticException("Not Eligible");

[Link]("Eligible");

Output

Exception in thread "main"


[Link]: Not Eligible

Example with try-catch

public class Demo {

public static void main(String[] args) {

try {

int age = 15;

if(age < 18){

throw new Exception("Age must be at least 18");

}
}

catch(Exception e){

[Link]([Link]());

Output

Age must be at least 18

throws Keyword

The throws keyword is used in the method declaration.

It tells the caller,

"This method may throw an exception. Handle it where you call me."

Syntax

returnType methodName() throws ExceptionName

Example

import [Link].*;

public class Demo {

static void readFile() throws IOException {

FileReader file = new FileReader("[Link]");

public static void main(String[] args) {

try {

readFile();

catch(IOException e){
[Link]("File not found");

Difference Between throw and throws

throw throws

Used inside a method Used in method declaration

Throws one exception object Declares one or more exceptions

Followed by new Exception() Followed by exception class names

Transfers control immediately Informs the caller about possible exceptions

Example

throw new ArithmeticException();

Example

void test() throws IOException

Example

throw new ArithmeticException();

Example

void test() throws IOException

Multiple catch Blocks

One try block can have multiple catch blocks.


Example

public class Demo {

public static void main(String[] args) {

try {

int arr[] = new int[3];

arr[5] = 10;

catch(ArrayIndexOutOfBoundsException e){

[Link]("Invalid Index");

catch(ArithmeticException e){

[Link]("Arithmetic Error");

catch(Exception e){

[Link]("Some Other Error");

Output

Invalid Index
Order of Catch Blocks

Always place specific exceptions first and the general Exception class last.

Correct

try {

}
catch(ArithmeticException e){

}
catch(Exception e){

Wrong

try {

}
catch(Exception e){

}
catch(ArithmeticException e){

This causes a compile-time error because Exception already catches all exceptions, making the later
ArithmeticException catch block unreachable.

Exception Hierarchy (Basic Overview)

Java exceptions are organized in a class hierarchy.

Object
|
Throwable
/ \
Error Exception
|
-------------------------
| |
RuntimeException Checked Exceptions
|
-------------------------------
| | |
Arithmetic NullPointer ArrayIndexOutOfBounds
Exception Exception Exception
Explanation

• Object: Root class of all Java classes.

• Throwable: Parent of everything that can be thrown.

• Error: Serious problems (e.g., OutOfMemoryError) that applications usually should not
handle.

• Exception: Conditions that applications can catch and recover from.

• RuntimeException: Parent class of unchecked exceptions.

Common Exceptions in Java

Exception Cause

ArithmeticException Divide by zero

NullPointerException Using a null object reference

ArrayIndexOutOfBoundsException Invalid array index

NumberFormatException Invalid string-to-number conversion

FileNotFoundException File does not exist

IOException Input/output error

ClassNotFoundException Class cannot be found

Complete Example

public class Demo {

public static void main(String[] args) {

[Link]("Program Started");

try {

int[] numbers = {10, 20, 30};

[Link](numbers[5]); // Causes exception

catch(ArrayIndexOutOfBoundsException e){

[Link]("Array index is out of range.");


}

finally{

[Link]("Cleanup completed.");

[Link]("Program Ended");

Output

Program Started
Array index is out of range.
Cleanup completed.
Program Ended

Summary

Concept Purpose

Exception An event that interrupts the normal flow of a program

Exception Handling Prevents the program from crashing and allows graceful recovery

try Contains code that may throw an exception

catch Handles a specific exception

finally Executes whether an exception occurs or not, typically for cleanup

Checked Exception Checked by the compiler and must be handled or declared

Unchecked Exception Occurs at runtime and handling is optional

throw Explicitly throws an exception object

throws Declares that a method may throw one or more exceptions

Multiple catch Handles different exception types separately

Exception Hierarchy Organizes throwable classes from Throwable down to specific exception types
Problem 1: Divide by Zero Exception

Problem Statement

Write a Java program to divide two integers.

• Initialize two integers.

• Set the second number to 0.

• Use try-catch to handle the exception.

• Display an appropriate error message instead of crashing the program.

• Expected Output
• Error: Cannot divide by zero.
Program continues successfully.

Problem 2: Array Index Out of Bounds Exception

Problem Statement

Write a Java program to:

• Create an integer array of size 5.

• Try to access the element at index 7.

• Handle the exception using try-catch.

• Print a suitable message.

Expected Output
Error: Invalid array index.
Program completed.

Problem 3: Number Format Exception

Problem Statement

Write a Java program to:

• Store the string "ABC".


• Convert it into an integer using [Link]().
• Handle the exception if the string cannot be converted.

Expected Output
Error: Invalid number format.
Program finished.

Problem 4: User-Defined Exception

Problem Statement
Create your own exception named InvalidAgeException.

Requirements:

• If a person's age is less than 18, throw the custom exception.


• Display the exception message using try-catch.
• Otherwise, print "Eligible to vote."

Expected Output
Age must be 18 or above.

Problem Statement

Write a Java program that:

• Creates an integer array with 3 elements.


• Takes a number from a string using [Link]().
• Divides 100 by the converted number.
• Stores the result in the array at index 5.
• Handle the following exceptions using separate catch blocks:
o NumberFormatException
o ArithmeticException
o ArrayIndexOutOfBoundsException
• Print "Program Ended" using the finally block.

Expected Output (with input "0")


Cannot divide by zero.
Program Ended

You might also like