0% found this document useful (0 votes)
4 views8 pages

Unit III, P3

This document covers Exception Handling in Java, detailing concepts such as try-catch blocks, multiple catch blocks, nested try blocks, and the throw statement. It explains built-in exceptions, including checked and unchecked exceptions, and provides examples of handling various exceptions like ArithmeticException and ArrayIndexOutOfBoundsException. The document emphasizes the importance of managing runtime errors to maintain the normal flow of program execution.

Uploaded by

KUSH SHARMA
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)
4 views8 pages

Unit III, P3

This document covers Exception Handling in Java, detailing concepts such as try-catch blocks, multiple catch blocks, nested try blocks, and the throw statement. It explains built-in exceptions, including checked and unchecked exceptions, and provides examples of handling various exceptions like ArithmeticException and ArrayIndexOutOfBoundsException. The document emphasizes the importance of managing runtime errors to maintain the normal flow of program execution.

Uploaded by

KUSH SHARMA
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
You are on page 1/ 8

JAVA(UGCA-1932)

UNIT-III, PART-III

Course Code: UGCA1932 (PTU)


Course Name: Programming in Java
Course: BCA, Semester: 5th
UNIT-III, PART-III
Exception Handling: Introduction, Try and Catch Blocks, Multiple Catch,
Nested Try, Finally, Throw Statement, Built-In Exceptions.

Introduction:
In Java, Exception is an unwanted or unexpected event, which occurs during the execution of
a program, i.e. at run time, that destroy the normal flow of the program’s instructions. Exceptions
can be caught and handled by the program. When an exception occurs within a method, it creates
an object. This object is called the exception object. It contains information about the exception,
such as the name and description of the exception and the state of the program when the
exception occurred.
Exception Handling in Java is one of the effective means to handle runtime errors so that the
regular flow of the application can be preserved. Java Exception Handling is a mechanism to
handle runtime errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Exceptions can be categorized in two ways:
1. Built-in Exceptions

 Checked Exception
 Unchecked Exception

2. User-Defined Exceptions
JAVA(UGCA-1932)
UNIT-III, PART-III

1. Built-in Exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are
suitable to explain certain error situations.
 Checked Exceptions: Checked exceptions are called compile-time exceptions because
these exceptions are checked at compile-time by the compiler.
 Unchecked Exceptions: The unchecked exceptions are just opposite to the checked
exceptions. The compiler will not check these exceptions at compile time

2. User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such
cases, users can also create exceptions, which are called ‘user-defined Exceptions’.

Exception Handling with Try-Catch Block:


Java provides a try-catch block to handle exceptions. Code that may cause an exception is
placed inside the try block, and the exception is caught in the catch block.

Syntax:
try {
// Code that might throw an exception
} catch (ExceptionType1 e1) {
// Code to handle exception type 1
}

 try: Contains code that might throw an exception.


 catch: Catches and handles the specific exception.

Example of Try-Catch:
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
// This will cause an ArithmeticException
System.out.println(result);
} catch (ArithmeticException a) {
System.out.println("Cannot divide by zero.");
}
}
}

Output:
Cannot divide by zero.
JAVA(UGCA-1932)
UNIT-III, PART-III

In this example, dividing by zero triggers an ArithmeticException, which is caught by the


catch block.

Multiple Catch Blocks:


A try block can be followed by multiple catch blocks to handle different types of exceptions.

Example:
public class Main {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]);
// ArrayIndexOutOfBoundsException
int result = 10 / 0;
// ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds.");
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
}
}

Output:

Array index is out of bounds.

 The first exception (ArrayIndexOutOfBoundsException) is caught and handled. If


multiple exceptions occur, only the first encountered exception is handled, and the
program stops.

The finally Block:

The finally block is used to execute important code such as closing resources (files, streams,
etc.), whether or not an exception occurs. The code in finally always executes after the try-
catch blocks.

Example:

public class Main {


public static void main(String[] args) {
try {
JAVA(UGCA-1932)
UNIT-III, PART-III

int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: Cannot divide
by zero.");
} finally {
System.out.println("This block always executes.");
}
}
}

Output:

Exception caught: Cannot divide by zero.


This block always executes.

The finally block will execute whether an exception is thrown or not.

Nested Try:
Nested try blocks refer to the use of one try block inside another try block. his allows you to
handle different levels of exceptions separately. Each inner try block can have its own catch
and finally blocks.

Syntax of Nested Try Blocks:


try {
// Outer try block
try {
// Inner try block
} catch (ExceptionType e) {
// Handle exception of the inner try block
}
} catch (ExceptionType e) {
// Handle exception of the outer try block
}
Example of Nested Try Blocks:

public class Main {


public static void main(String[] args) {
try {
// Outer try block
int[] numbers = {1, 2, 3};
System.out.println("Accessing an element: " +
numbers[3]); // ArrayIndexOutOfBoundsException
JAVA(UGCA-1932)
UNIT-III, PART-III

try {
// Inner try block
int result = 10 / 0; // ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Inner catch: Cannot divide
by zero.");
}

} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Outer catch: Array index is out
of bounds.");
}
}
}

Output:

Outer catch: Array index is out of bounds.

Explanation:

1. The outer try block tries to access an array element that does not exist (numbers[3]), which
throws an ArrayIndexOutOfBoundsException. This is caught by the outer catch block.
2. The inner try block tries to perform a division by zero (10 / 0), which would throw an
ArithmeticException, but this exception is not reached because the outer exception already
occurred and was handled.

Key Points to Remember:

 The inner try-catch block handles exceptions thrown within the inner block, while the
outer try-catch block handles exceptions from both the outer block and any uncaught
exceptions from the inner block.

 If an exception is caught by an inner catch, the outer catch block won't be executed for that
exception, but if the exception is not handled by the inner block, it can be passed up to the
outer catch block.
JAVA(UGCA-1932)
UNIT-III, PART-III

Throw Statement:
In the Java throw keyword is used to throw an exception explicitly. The Exception has some
message with it that provides the error description. These exceptions may be related to user inputs,
server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used
to throw a custom exception.

We can also define our own set of conditions and throw an exception explicitly using throw
keyword. For example, we can throw ArithmeticException if we divide a number by another
number. Here, we just need to set the condition and throw exception using throw keyword.

Syntax:
throw new exception_class("error message");

Example:
public class Main {
public static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You
must be at least 18 years old.");
} else {
System.out.println("Access granted.");
}
}

public static void main(String[] args) {


checkAge(16); // Will throw an exception
}
}
OUTPUT
JAVA(UGCA-1932)
UNIT-III, PART-III

Built-In Exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are
suitable to explain certain error situations. Java provides several built-in exceptions:

1. Arithmetic exception: It is thrown when an exceptional condition has occurred in an


arithmetic operation.

Example:
class ArithmeticException_Demo {
public static void main(String[] args) {
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
System.out.println("Result = " + c);
} catch (ArithmeticException e) {
System.out.println("Can't divide a number by 0");
}
}
}
OUTPUT
Can’t divide a number by 0
2. ArrayIndexOutOfBounds Exception: It is thrown to indicate that an array has been
accessed with an illegal index. The index is either negative or greater than or equal to the
size of the array.

Example:
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
try {
System.out.println(numbers[3]);
// ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds: " + e);
}
}
}

OUTPUT
JAVA(UGCA-1932)
UNIT-III, PART-III

3. ClassNotFoundException: This Exception is raised when we try to access a class whose


definition is not found.

4. FileNotFoundException: This Exception is raised when a file is not accessible or does not
open.
5. IOException: It is thrown when an input-output operation failed or interrupted.
6. NoSuchMethodException: t is thrown when accessing a method which is not found.
7. NumberFormatException: This exception is raised when a method could not convert a
string into a numeric format.
8. StringIndexOutOfBoundsException: It is thrown by String class methods to indicate that
an index is either negative than the size of the string.

You might also like