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

Exception Handling in Java

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)
3 views18 pages

Exception Handling in Java

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

Exception Handling

Object Oriented Programming

By: Engr. Jamsher Bhanbhro


Lecturer at Department of Computer Systems Engineering,
Mehran University of Engineering & Technology Jamshoro
Books Recommendation
Books Recommended
1. Head First Java by Kathy Sierra & Bert Bates.
2. Beginning Programming with Java For Dummies by Barry Burd
3. Java: Programming Basics for Absolute Beginners by Nathan Clark
4. Object Oriented Programming in Java by Rick Halterman
Websites Recommended:
DataFlair, Educative, course era
Exception
• An exception is an event or condition that disrupts the normal flow of
a program's execution. Exceptions represent errors or unexpected
situations that can occur during the execution of a Java program.
These exceptions can be caused by a variety of factors, such as invalid
input, resource unavailability, or logic errors.
• It is always better practice to handle exception to avoid unwanted
problems.
• For example in normal if your program prints five statements but if
exception occurs in second statement other three statements will be
missed or not executed by the compiler.
Exception Handling
• Exception handling is the process of dealing with these exceptional
situations in a controlled and organized manner. It allows a Java
program to gracefully handle errors and recover from unexpected
situations without terminating abruptly.
• Exception handling provides a mechanism for separating error-
handling code from the normal flow of the program, making code
more robust and maintainable.
• Exception handling will help compiler to reach at the end of your
program even with facing exception.
• In our last example if we will handle exception last three lines will be
executed by the compiler too.
Exception Types
• In Java we have two types of exception
• Checked & Un-Checked Exceptions
• Checked Exceptions: These are exceptions that are checked by the
compiler at compile-time. Code that can potentially throw checked
exceptions must be enclosed within try-catch blocks or declared in
method signatures using the throws keyword. FileNotFoundException
and IOException, ClassNotFoundException: Occurs when the Java
runtime cannot find a class at runtime that was expected to be present.
These are examples of Checked Exception.
Exception Types
• Unchecked Exceptions (Runtime Exceptions): These are exceptions
that are not checked by the compiler at compile-time. They typically
indicate programming errors, such as null pointer exceptions or array
index out of bounds exceptions.
• Exception Hierarchy: Java has a hierarchical structure for exceptions,
with the [Link] class at the top of the hierarchy.
Throwable has two main subclasses: [Link] (for checked
exceptions) and [Link] (for unchecked
exceptions). These subclasses have many more specialized exception
classes.
Handling the Exception
• Try-Catch Blocks: To handle exceptions, Java provides the try-catch
statement. Code that may throw an exception is placed within the try
block, and the corresponding exception-handling code is placed within
the catch block. Syntax is given below.
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Exception handling code
}
Handling the Exception
• Finally Blocks: A finally block can be used to specify code that must be
executed whether or not an exception is thrown. It is often used for cleanup
operations, such as closing files or releasing resources.
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Exception handling code
} finally {
// Code that always executes
}
Handling the Exception
• Throwing Exceptions: You can manually throw exceptions using the
throw statement. This allows you to create and throw custom
exceptions when specific conditions are met.

if (condition) {
throw new CustomException("This is a custom exception");
}
Java Exceptions Some Concepts
• In Java we can have multiple try-catch block in one program.
• In Java we cannot have multiple try blocks with a single catch block.
• But we can have nested try block & catch block for each try. Below is
example:
try {
// Outer try block
// Code that may throw exceptions

try {
// Inner try block
// Code that may throw exceptions
} catch (InnerException e) {
// Handle exceptions specific to the inner try block
}
} catch (OuterException e) {
// Handle exceptions specific to the outer try block
}
Java Exceptions Some Concepts
• In Java, we can have multiple catch blocks associated with a single try
block. For Example
try {
int result = 10 / 0; // ArithmeticException
String str = null;
[Link](); // NullPointerException
} catch (ArithmeticException e) {
[Link]("ArithmeticException: " + [Link]());
} catch (NullPointerException e) {
[Link]("NullPointerException: " + [Link]());
}
Java Exceptions
• ArithmeticException (Divide By Zero):when we try to divide a number by 0 it gives exception also
called Arithmetic Exception.
public class ArithmeticExceptionExample {
public static void main(String[] args) {
int numerator = 10;
int denominator = 0;
try {
int result = numerator / denominator; // Division by zero
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Caught an ArithmeticException: " + [Link]());
}
}
}
// always try to write those lines in try block which may produce exception. If there
is exception catch block statement will run otherwise catch block will be skipped
Java Exceptions
• IndexOutOfBoundsException: Pointing towards index which is out of bound.
public class IndexOutOfBoundsExceptionExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
try {
int value = numbers[4]; // Accessing an index out of bounds
[Link]("Value: " + value);
} catch (IndexOutOfBoundsException e) {
[Link]("Caught an IndexOutOfBoundsException: " +
[Link]());
}
}
}
Java Exceptions
• NullPointerException: In Java trying to refer a null object/variable is
called Null pointer exception.
public class NullPointerExceptionExample {
public static void main(String[] args) {
String text = null;
try {
int length = [Link](); // Accessing a method on a null object
[Link]("Length: " + length);
} catch (NullPointerException e) {
[Link]("Caught a NullPointerException: " + [Link]());
}
}
}
Java Exceptions
• IllegalArgumentExceptionExample:
public class IllegalArgumentExceptionExample {

public static void main(String[] args) {


int age = -5;
try {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
[Link]("Age: " + age);
} catch (IllegalArgumentException e) {
[Link]("Caught an IllegalArgumentException: " + [Link]());
}
}
}
Java Exceptions
• NumberFormatException (Parsing Strings to Numbers):Here, we try to parse an invalid numeric string
("abc123") using [Link](). This results in a NumberFormatException, which we catch and handle
with an error message.
public class NumberFormatExceptionExample {

public static void main(String[] args) {

String invalidNumber = "abc123"; // Invalid numeric string

try {

int num = [Link](invalidNumber); // Attempting to parse an invalid string

[Link]("Parsed Number: " + num);

} catch (NumberFormatException e) {

[Link]("NumberFormatException: Invalid numeric string.");

}}}
Java Exceptions
FileNotFoundException (File Handling): Handling exception so that if file is not found program should not terminate or crash.
import [Link];
import [Link];
import [Link];
public class FileNotFoundExceptionExample {
public static void main(String[] args) {
try {
File file = new File("[Link]"); // Trying to open a non-existent file
Scanner scanner = new Scanner(file);
while ([Link]()) {
[Link]([Link]());
}
[Link]();
} catch (FileNotFoundException e) {
[Link]("FileNotFoundException: The specified file was not found.");
}}}
Practice Questions
• Write a Java program that takes two integers as input from the user and attempts to
divide the first integer by the second. Handle the "Divide by Zero" exception
gracefully, providing an error message when the second integer is zero.
• Write a Java program that initializes an integer array of size N and prompts the
user for two inputs: the index at which to add an element and the value of the
element to be added. Implement proper exception handling to address the scenario
when the user attempts to add an element to an empty index (i.e., the index is out
of bounds). In such cases, catch the NullPointerException and provide a user-
friendly error message.
• Write a Java program that reads an integer input from the user. Implement proper
exception handling to catch the InputMismatchException when the user enters a
non-integer input. In such cases, display an error message and allow the user to re-
enter the integer input
• Write a Java program that initializes an integer array of size N and prompts the
user to enter an index. Implement proper exception handling to catch the
ArrayIndexOutOfBoundsException when the user enters an index that is out of
bounds (i.e., less than 0 or greater than or equal to N). In such cases, display an
error message and allow the user to re-enter a valid index.

You might also like