Session 24 - Exception Handling
Session 24 - Exception Handling
THROUGH JAVA
UNIT - IV
Session 24 - Exception Handling
1. Introduction
statement 1;
statement 2;
statement 3;
statement 4;
statement 5; // exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
If an exception arises at statement 5, the remaining statements (statement 6 through
statement 10) will not be executed. Exception handling allows the program to manage the
error at statement 5 and continue executing the subsequent statements, thereby maintaining
the normal flow of the application. This capability is crucial for ensuring that the program
remains functional and responsive even in the face of errors.
1. Throwable
● Definition: The base class for all errors and exceptions in Java. It has two main
subclasses: Error and Exception.
● Key Methods: getMessage(), printStackTrace(), toString()
2. Error
● Definition: Represents severe errors that are usually beyond the control of the
application. These errors are not meant to be caught by applications.
● Common Subclasses:
○ OutOfMemoryError
○ StackOverflowError
○ VirtualMachineError
3. Exception
Definition
The throw keyword is used to explicitly throw an exception from a method or a block of code.
When you use throw, you create an instance of an exception class and pass it to the Java
runtime, which then handles it according to the exception handling mechanism.
Syntax
throw new ExceptionType("Error message");
Example
Here’s an example of using the throw keyword to throw an ArithmeticException:
Definition
The throws keyword is used in a method declaration to specify that a method might throw one
or more exceptions. This informs the caller of the method that they need to handle these
exceptions or propagate them further.
Syntax
returnType methodName(parameters) throws ExceptionType1, ExceptionType2 {
// Method body
}
Example
Here’s an example of using the throws keyword to declare that a method may throw
IOException:
import java.io.*;
Practice Programs
Program 1: Using throw Write a Java program that throws a NumberFormatException if
the input is not a valid integer.
import java.util.Scanner;
import java.io.*;
Do It Yourself
1. Write a program that uses the throw keyword to throw a custom exception when an
invalid age (negative number) is provided.
2. Create a method that declares multiple exceptions using throws and handle them in the
main method.
3. Define a custom exception class and use it with the throw keyword in a Java program.
4. Write a program where an exception is thrown in one method and caught in another
method that calls it.
Quiz
1. Which keyword is used to explicitly throw an exception?
- A) throws
- B) throw
- C) try
- D) catch
Answer: B) throw
4. What will happen if you use throw without specifying an exception object?
- A) Compilation error
- B) Runtime exception
- C) The program will continue executing normally
- D) It will be ignored
Definition
The try block is used to enclose code that might throw an exception. It’s the starting point for
exception handling.
Syntax
try {
// Code that might throw an exception
}
Example
public class TryExample {
public static void main(String[] args) {
try {
int[] numbers = new int[5];
numbers[10] = 100; // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}
Explanation: In this example, the try block contains code that attempts to access an invalid
array index, which results in an ArrayIndexOutOfBoundsException.
Definition
The catch block is used to handle exceptions thrown by the try block. It catches exceptions of
specified types and allows you to handle them.
Syntax
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
Example
public class CatchExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught Exception: Division by zero is not allowed.");
}
}
}
Explanation: Here, the catch block handles the ArithmeticException thrown by the try
block and prints an appropriate message.
Definition
The finally block is used to execute code regardless of whether an exception was thrown or
not. It’s often used for closing resources like files or database connections.
Syntax
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute
}
Example
import java.io.*;
Practice Programs
Program 1: Nested Try-Catch-Finally Write a Java program that demonstrates the use of
nested try, catch, and finally blocks.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
Do It Yourself
1. Write a Java program that attempts to access a file that does not exist. Use try, catch,
and finally blocks to handle the exception and ensure that any resources are closed
properly.
2. Create a Java program that demonstrates handling multiple exceptions using multiple
catch blocks.
3. Write a program that opens a file for reading and ensures that the file is closed using the
finally block.
4. mplement a Java program that uses nested try, catch, and finally blocks to handle
exceptions and ensure proper cleanup.
Quiz
1. What will happen if an exception occurs in the try block?
- A) catch
- B) try
- C) finally
- D) throw
Answer: C) finally
- A) Yes
- B) No
- C) Only in Java 8 and later versions
- D) Only within a try-catch block
Answer: A) Yes
Definition
In Java, a try block can be followed by multiple catch blocks to handle different types of
exceptions that may be thrown. Each catch block is designed to handle a specific type of
exception. When an exception is thrown, the control transfers to the appropriate catch block
based on the type of the exception.
Syntax
try {
// Code that might throw exceptions
} catch (ExceptionType1 e1) {
// Code to handle ExceptionType1
} catch (ExceptionType2 e2) {
// Code to handle ExceptionType2
} catch (ExceptionType3 e3) {
// Code to handle ExceptionType3
}
Example
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int[] numbers = new int[5];
numbers[10] = 100; // ArrayIndexOutOfBoundsException
int result = 10 / 0; // ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " +
e.getMessage());
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
} catch (Exception e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}
Explanation: In this example:
Advantages
- Specific Handling: Allows different responses for different types of exceptions.
- Granularity: Provides control over exception handling by addressing each exception
type separately.
Example
public class MultipleExceptionsHandling {
public static void main(String[] args) {
try {
String str = null;
int length = str.length(); // NullPointerException
Practice Programs
Program 1: Handling Multiple Exceptions
Create a program to show that catch blocks should be ordered from the most specific exception
type to the most general.
Do It Yourself
1. Write a Java program that handles IOException, FileNotFoundException, and
NumberFormatException using multiple catch blocks.
2. Define a custom exception and use it in a try-catch block along with standard
exceptions.
3. Write a program that demonstrates handling an exception thrown from within a catch
block.
4. Create a Java program that shows how exceptions are propagated through methods
with multiple catch blocks.
5. Write a program that handles multiple exceptions using a single catch block.
Quiz
1. What will happen if multiple catch blocks handle the same type of exception?
Answer: D) The first catch block that matches the exception will execute.
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught");
} catch (Exception e) {
System.out.println("Exception caught");
}
- A) ArithmeticException caught
- B) Exception caught
- C) Both messages
- D) No output
try {
throw new FileNotFoundException();
} catch (IOException e) {
System.out.println("IOException caught");
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException caught");
}
- A) IOException caught
- B) FileNotFoundException caught
- C) Both messages
- D) No output
6. Class Throwable
Class Throwable
The Throwable class in Java is the superclass of all errors and exceptions in the Java
language. This document provides an in-depth exploration of the Throwable class, including its
methods, examples, explanations, practice programs, homework questions, and multiple-choice
questions.
Definition
The Throwable class is the root class for all errors and exceptions in Java. It has two main
subclasses: Error and Exception. All exceptions and errors are derived from this class,
making it the base class for error handling in Java.
Hierarchy
- java.lang.Object
- java.lang.Throwable
- java.lang.Error
- java.lang.Exception
- java.lang.RuntimeException
- Other Exception subclasses (e.g., IOException,
SQLException)
Syntax
The Throwable class has two main constructors:
public class Throwable {
// Default constructor
public Throwable();
Methods
Some of the key methods in the Throwable class are:
Examples
Practice Programs
Program 1: Handling Generic Throwable Write a Java program that demonstrates how to
catch all types of throwables and print their messages and stack traces.
@Override
public void printStackTrace() {
System.out.println("Custom stack trace message:");
super.printStackTrace();
}
}
Do It Yourself
1. Write a program that demonstrates how to catch a Throwable and extract its message
and stack trace.
2. Create a custom exception class that extends Throwable. Write a program that throws
and catches this custom exception.
3. Develop a program that throws a Throwable with a cause and demonstrates how to
access the cause of the throwable.
4. Write a program that uses printStackTrace() to print a stack trace and explains the
information provided.
5. Modify a program to use multiple catch blocks, including one for Throwable, to
demonstrate how different types of exceptions are handled.
Quiz
1. What is the root class for all exceptions and errors in Java?
- A) Error
- B) Exception
- C) Throwable
- D) RuntimeException
Answer: C) Throwable
- A) getMessage()
- B) toString()
- C) getCause()
- D) printStackTrace()
Answer: C) getCause()
try {
throw new Throwable("Exception Message");
} catch (Throwable t) {
System.out.println(t.getMessage());
}
- A) Exception Message
- B) Throwable
- C) null
- D) No output
4. Which method in the Throwable class prints the stack trace to the standard error
stream?
- A) getMessage()
- B) printStackTrace()
- C) getCause()
- D) toString()
Answer: B) printStackTrace()
7. Unchecked Exceptions
Unchecked Exceptions
Unchecked exceptions are a critical concept in Java exception handling. They are exceptions
that do not need to be declared in a method's throws clause and are typically used to signal
programming errors that should be fixed in the code.
Definition
Unchecked exceptions are exceptions that derive from the RuntimeException class. Unlike
checked exceptions, these do not need to be caught or declared thrown in the method
signatures. They are used to indicate errors that are usually caused by bugs in the code or
incorrect usage of APIs.
Hierarchy
- java.lang.Object
- java.lang.Throwable
- java.lang.Exception
- java.lang.RuntimeException
- Example subclasses: NullPointerException,
ArrayIndexOutOfBoundsException,
ArithmeticException
Example 1: NullPointerException
public class NullPointerExample {
public static void main(String[] args) {
String str = null;
try {
int length = str.length(); // This line will throw NullPointerException
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " + e.getMessage());
}
}
}
Explanation: The NullPointerException occurs because str is null, and calling a
method on null references results in this exception.
Example 2: ArrayIndexOutOfBoundsException
public class ArrayIndexOutOfBoundsExample {
public static void main(String[] args) {
int[] array = new int[5];
try {
int value = array[10]; // This line will throw
ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " +
e.getMessage());
}
}
}
Explanation: Accessing an array with an invalid index (10) throws an
ArrayIndexOutOfBoundsException.
Example 3: ArithmeticException
public class ArithmeticExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This line will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
}
}
}
Explanation: Dividing by zero throws an ArithmeticException.
Example 4: IllegalArgumentException
public class IllegalArgumentExceptionExample {
public static void validateAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
Do It Yourself
1. Write a program that handles NullPointerException and demonstrates how to
avoid this exception.
2. Create a program that demonstrates ArrayIndexOutOfBoundsException and
discuss how to avoid it.
3. Define a custom unchecked exception and write a program to throw and catch this
custom exception.
4. Develop a program that performs division and handles ArithmeticException for
division by zero.
5. Write a program that validates method arguments and throws
IllegalArgumentException for invalid inputs.
Quiz
1. Which class is the direct superclass of all unchecked exceptions in Java?
- A) Exception
- B) RuntimeException
- C) Throwable
- D) Error
Answer: B) RuntimeException
- A) Checked Exception
- B) Unchecked Exception
- C) Error
- D) RuntimeException
8. Checked Exceptions
Checked Exceptions
Checked exceptions are exceptions that are checked at compile-time. These exceptions require
explicit handling through try-catch blocks or by declaring them using the throws keyword in the
method signature. They are used to handle exceptional conditions that a program should
anticipate and recover from.
Definition
Checked exceptions are exceptions that are checked by the Java compiler at compile time.
Unlike unchecked exceptions, the compiler ensures that these exceptions are either caught or
declared to be thrown. They typically represent conditions that a program might want to handle,
such as I/O errors or invalid data.
Hierarchy
- java.lang.Object
- java.lang.Throwable
- java.lang.Exception
- java.io.IOException
- java.sql.SQLException
- java.lang.ClassNotFoundException
- and more...
Common Checked Exceptions
- IOException: Signals that an I/O operation failed or was interrupted.
- SQLException: Signals that a database access error or other errors related to SQL
operations occurred.
- ClassNotFoundException: Indicates that a requested class was not found.
Practice Programs
Program 1: Handle Multiple Checked Exceptions Write a Java program that handles multiple
checked exceptions (IOException, SQLException) in a single try-catch block.
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username",
"password");
conn.close();
} catch (IOException | SQLException e) {
System.out.println("Caught Exception: " + e.getClass().getSimpleName() + "
- " + e.getMessage());
}
}
}
Program 2: Exception Propagation Write a program that demonstrates exception propagation
through methods.
Do It Yourself
1. Write a program that reads from a file and handles IOException. Ensure the file is
closed properly in case of an exception.
2. Create a program that connects to a database and handles SQLException for potential
connection failures.
3. Define a custom checked exception, throw it from a method, and handle it in the main
method.
4. Write a program demonstrating how exceptions propagate through method calls.
5. Write a program that handles multiple checked exceptions (IOException,
ClassNotFoundException) in separate try-catch blocks.
Quiz
1. Which of the following is a checked exception?
- A) NullPointerException
- B) ArrayIndexOutOfBoundsException
- C) IOException
- D) ArithmeticException
Answer: C) IOException
3. What is the output of the following code if the file does not exist?
import java.io.FileReader;
import java.io.IOException;
Answer: B) Exception: file.txt (The system cannot find the file specified)
4. Which keyword is used to declare that a method can throw a checked exception?
- A) throws
- B) throws
- C) throw
- D) catch
Answer: A) throws
Answer: B) To inform the compiler that the method may throw this exception
References
End of Session - 24