Unit III, P3
Unit III, P3
UNIT-III, PART-III
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’.
Syntax:
try {
// Code that might throw an exception
} catch (ExceptionType1 e1) {
// Code to handle exception type 1
}
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
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:
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:
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:
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.
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:
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.
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.");
}
}
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:
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
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.