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

Exception Handling (2)

The document provides an overview of exceptions in Java, explaining their nature as events that disrupt the normal flow of program execution and categorizing them into checked, unchecked, and errors. It details exception handling mechanisms, including try-catch blocks, throwing exceptions, and using finally clauses to ensure resource management. Additionally, it includes examples of common exceptions and sample questions for practical application of the concepts discussed.

Uploaded by

albin.23pmc101
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 views

Exception Handling (2)

The document provides an overview of exceptions in Java, explaining their nature as events that disrupt the normal flow of program execution and categorizing them into checked, unchecked, and errors. It details exception handling mechanisms, including try-catch blocks, throwing exceptions, and using finally clauses to ensure resource management. Additionally, it includes examples of common exceptions and sample questions for practical application of the concepts discussed.

Uploaded by

albin.23pmc101
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/ 22

Exception

An exception (or exceptional event) is a problem that arises during the execution of a
program.

When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, therefore, these exceptions are to be handled

In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.

An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.

● A user has entered an invalid data.


● A file that needs to be opened cannot be found.
● A network connection has been lost in the middle of communications or the JVM has
run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others
by physical resources that have failed in some manner.

The Exception Handling in Java is one of the powerful mechanisms to handle the runtime
errors so that the normal flow of the application can be maintained.

statement 1;
Suppose there are 8 statements in a Java
statement 2; program and an exception occurs at
statement 3; statement 5; the rest of the code will not
statement 4; be executed, i.e., statements 6 ,7,8 will
not be executed. However, when we
statement 5;//exception occurs
perform exception handling, the rest of
statement 6;
the statements will be executed. That is
statement 7;
why we use exception handling in Java.
statement 8;
Hierarchy of Java Exception classes
Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is considered
as the unchecked exception. However, according to Oracle, there are three types of
exceptions namely:

● Checked Exception
Exceptions that are checked at compile-time (e.g., IOException, SQLException).

● Unchecked Exception
Exceptions that are not checked at compile-time (e.g., ArithmeticException,
NullPointerException)

● Error
Severe problems that are not usually handled by the application (e.g., OutOfMemoryError).

.
Checked Exceptions in Java
A checked exception (also called a logical exception) in Java is something that has gone
wrong in your code and is potentially recoverable. For example, if there’s a client error when
calling another API, we could retry from that exception and see if the API is back up and
running the second time. A checked exception is caught at compile time so if something
throws a checked exception the compiler will enforce that you handle it.

Unchecked Exceptions in Java


An unchecked exception (also known as an runtime exception) in Java is something that
has gone wrong with the program and is unrecoverable. Just because this is not a compile
time exception, meaning you do not need to handle it, that does not mean you don’t need to
be concerned about it.

The most common runtime exception is the good old NullPointerException which is when
you are trying to access a variable or object that doesn’t exist.
1. Handling Exceptions

import java.io.FileReader; This program will throw an exception when


import java.io.IOException; the text file named ‘somefile.txt’ does not
exist
public class CheckedExceptionExample {
public static void main(String[] args) { And the following message will be
try { displayed
FileReader file = new
FileReader("somefile.txt"); An IOException occurred: somefile.txt
file.read(); (The system cannot find the file
file.close(); specified)
} catch (IOException e) {
System.out.println("An IOException
occurred: " + e.getMessage());
}
}
}

public class ExceptionOverview {


public static void main(String[] args) {
int[] numbers = {1, 2, 3};
try {
System.out.println(numbers[3]); // This will throw
ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
}
System.out.println("Program continues...");
}}

output
Exception caught: java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for
length 3
Program continues...
2. Declaring Exceptions

Purpose: Allows a method to specify which exceptions it might throw, ensuring that callers
of the method are aware of and can handle potential exceptions.
Syntax:
void methodName() throws ExceptionType {
// method code
}

Example:
import java.io.*;

public class DeclaringExceptions {


public static void main(String[] args) {
try {
readFile("test.txt");
} catch (IOException e) {
System.out.println("Exception caught: " + e);
}
}

public static void readFile(String fileName) throws IOException {


FileReader file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
System.out.println(line);
}
}
3. Throwing Exceptions

Purpose: Allows the programmer to explicitly throw an exception when a certain condition
is met.
Syntax: throw new ExceptionType("Error message");

Example:

public class ThrowingExceptions {


public static void main(String[] args) {
try {
checkAge(15);
} catch (Exception e) {
System.out.println("Exception caught: " + e.getMessage());
}
}

public static void checkAge(int age) throws Exception {


if (age < 18) {
throw new Exception("Age must be 18 or older");
}
System.out.println("Age is valid");
}
}
4. Catching Exceptions

Purpose: Allows a program to catch and handle exceptions, preventing the program from
terminating unexpectedly.
Syntax:
try {
// code that may throw an exception
} catch (ExceptionType e) {
// code to handle the exception
}

Example:

public class CatchingExceptions {


public static void main(String[] args) {
try {
int result = divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}

public static int divide(int a, int b) {


return a / b;
}
}
5. Getting Information from Exceptions

Purpose: Provides methods to retrieve information from an exception object.

Common Methods:

getMessage(): Returns the detail message string of the throwable.


printStackTrace(): Prints the throwable and its backtrace to the standard error stream.

Example:
public class ExceptionInfo {

public static void main(String[] args) {

try {

int[] numbers = new int[5];

numbers[10] = 50;

} catch (ArrayIndexOutOfBoundsException e) {

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

System.out.println("\n Stack trace will be printed next \n");

e.printStackTrace();

}
6. The finally Clause

Purpose: The finally block is used to execute important code such as closing resources,
regardless of whether an exception is handled or not.

Syntax:

try {
// code that may throw an exception
} catch (ExceptionType e) {
// code to handle the exception
} finally {
// code to be executed no matter what
}

Example:

import java.io.*;

public class FinallyClause {


public static void main(String[] args) {
FileReader file = null;
try {
file = new FileReader("test.txt");
BufferedReader reader = new BufferedReader(file);
System.out.println(reader.readLine());
} catch (IOException e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
try {
if (file != null) {
file.close();
}
} catch (IOException e) {
System.out.println("Error closing file: " + e.getMessage());
}
System.out.println("Finally block executed"); } }}
Java exceptions are events that disrupt the normal flow of a program's execution. They
can arise from various scenarios, such as invalid user input, hardware failures, or
network issues. Understanding the different types of exceptions and how to handle
them is crucial for robust Java programming.
===============================================================

Types of Exceptions
1. Checked Exceptions:
● These are exceptions that the compiler checks at compile-time. If a
method can throw a checked exception, it must either handle it with a
try-catch block or declare it in its method signature using the throws
keyword.
● Examples include:: Issues related to input/output operations.

2. Unchecked Exceptions:
● These exceptions are not checked at compile-time but occur at runtime.
They extend RuntimeException.
● Examples include:: Occurs when an arithmetic operation fails, such as
division by zero.

Examples:

ArithmeticException: Raised when an arithmetic operation fails, such as


division by zero.

NullPointerException: Occurs when attempting to use an object reference


that has not been initialized.
ArrayIndexOutOfBoundsException: Thrown when trying to access an array
with an invalid index

1. ArithmeticException

This exception occurs when an arithmetic operation fails, such as division


by zero.

public class ArithmeticExceptionExample {

public static void main(String[] args) {

int x = 10;

int y = 0;

try {

int result = x / y; // This will throw ArithmeticException

System.out.println("Result: " + result);

} catch (ArithmeticException e) {

System.err.println("Error: " + e.getMessage());

}
}

Output:

Error: / by zero

2. NullPointerException

This exception occurs when trying to access an object or variable that has
not been initialized (i.e., it is null).

public class NullPointerExceptionExample {

public static void main(String[] args) {

String str = null;

try {

System.out.println("Length: " + str.length()); // This will throw


NullPointerException
} catch (NullPointerException e) {

System.err.println("Error: " + e.getMessage());

Output:

Error: Cannot invoke "String.length()" because "str" is null

3. ArrayIndexOutOfBoundsException

This exception is thrown when trying to access an invalid index of an array.

public class ArrayIndexOutOfBoundsExample {

public static void main(String[] args) {

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


try {

System.out.println(numbers[3]); // This will throw


ArrayIndexOutOfBoundsException

} catch (ArrayIndexOutOfBoundsException e) {

System.err.println("Error: " + e.getMessage());

Output:

Error: Index 3 out of bounds for length 3

4. NumberFormatException

This exception occurs when trying to convert a string to a numeric type


but the string does not have the appropriate format.
public class NumberFormatExceptionExample {

public static void main(String[] args) {

String invalidNumber = "abc";

try {

int number = Integer.parseInt(invalidNumber); // This will throw


NumberFormatException

System.out.println("Number: " + number);

} catch (NumberFormatException e) {

System.err.println("Error: " + e.getMessage());

Output:

Error: For input string: "abc"


5. IllegalArgumentException

This exception is thrown when a method receives an argument that is


inappropriate or outside the expected range.

public class IllegalArgumentExceptionExample {

public static void main(String[] args) {

try {

setAge(-5); // This will throw IllegalArgumentException

} catch (IllegalArgumentException e) {

System.err.println("Error: " + e.getMessage());

public static void setAge(int age) {

if (age < 0) {

throw new IllegalArgumentException("Age cannot be negative.");


}

System.out.println("Age set to: " + age);

Output:

Error: Age cannot be negative.

3. Errors:
● These are serious issues that applications should not try to catch. They
usually indicate problems with the Java Runtime Environment (JRE) itself.
● Examples include:: Occurs when the JVM runs out of memory.

Exception Handling Mechanism


Java provides several keywords for handling exceptions:

● try: A block of code that may throw an exception is wrapped in a try block.
● catch: This block catches and handles exceptions thrown by the try block.
● finally: This block executes code after the try-catch blocks, regardless of whether
an exception occurred or not.
● throw: Used to explicitly throw an exception.
● throws: Declares that a method can throw one or more exceptions.

Example Code
Here’s a simple example demonstrating exception handling in Java:

public class ExceptionHandlingExample {


public static void main(String[] args) {
try {
int result = divide(10, 0); // This will throw
ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.err.println("Error: " + e.getMessage());
} finally {
System.out.println("Execution completed.");
}
}

public static int divide(int a, int b) {


return a / b; // Division by zero will cause an exception
}
}
Output

Error: / by zero
Execution completed.

In this example:

● The divide method attempts to divide two integers. If the denominator is zero, it
throws an ArithmeticException.
● The exception is caught in the catch block, which prints an error message.
● The finally block executes regardless of whether an exception occurred,
indicating that execution is complete.

Conclusion
Understanding and effectively managing exceptions in Java is essential for creating
reliable applications. By using appropriate handling mechanisms and being aware of the
types of exceptions that can occur, developers can ensure their programs run smoothly
and handle errors gracefully.
===============================================================

Sample Questions

● Write a Java program that reads a file named input.txt and displays its contents.
Handle exceptions for file not found and I/O errors.

● Create a program that takes two integers as input from the user and performs
division. Handle ArithmeticException for division by zero
● Implement a method that reads integers from a file named numbers.txt, calculates
their average, and handles exceptions for I/O and number format issues.

● Write a program that demonstrates the use of try-catch-finally blocks by attempting


to read from a file that does not exist.

● Design a class InvalidInputException that extends Exception. Write a program that


throws this exception if the user inputs a negative number.

Ref

Exceptions - Java Programming


https://rollbar.com/blog/how-to-handle-checked-unchecked-exceptions-in-java/#:~:text=A%2
0checked%20exception%20is%20caught%20at%20compile%20time%20whereas%20a,t%
20required%20to%20be%20handled.

You might also like