0% found this document useful (0 votes)
2 views37 pages

Session 24 - Exception Handling

This document provides an overview of exception handling in Java, detailing its importance, advantages, and the hierarchy of standard exception classes. It explains the use of keywords 'throw' and 'throws' for managing exceptions, along with examples of try, catch, and finally blocks for error handling. Additionally, it includes practice programs and quizzes to reinforce understanding of the concepts presented.

Uploaded by

pavankumarvoore3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views37 pages

Session 24 - Exception Handling

This document provides an overview of exception handling in Java, detailing its importance, advantages, and the hierarchy of standard exception classes. It explains the use of keywords 'throw' and 'throws' for managing exceptions, along with examples of try, catch, and finally blocks for error handling. Additionally, it includes practice programs and quizzes to reinforce understanding of the concepts presented.

Uploaded by

pavankumarvoore3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

OBJECT-ORIENTED PROGRAMMING

THROUGH JAVA

UNIT - IV
Session 24 - Exception Handling
1. Introduction

What is Exception Handling?


Exception handling is a programming mechanism designed to manage runtime errors, such as
ClassNotFoundException, IOException, SQLException, and RemoteException. It
allows developers to address and resolve these issues gracefully without abruptly terminating
the program.

Advantages of Exception Handling


The primary benefit of exception handling is that it ensures the continuous operation of an
application even when errors occur. Without exception handling, an error could halt the
execution of the program, preventing subsequent code from running. Here's an example to
illustrate this:

Consider a Java program with the following sequence of statements:

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.

2. Hierarchy of Standard Exception Classes


In Java, exception handling is structured around a class hierarchy that helps manage errors in a
systematic way. Here's an overview of the key classes and interfaces in the Java exception
hierarchy:

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: Represents conditions that a reasonable application might want to catch.


This is the superclass of all exceptions.
● Key Subcategories:
○ Checked Exceptions: Exceptions that must be either caught or declared in the
method where they might be thrown. They are checked at compile-time.
■ IOException: Represents general input/output errors.
■ SQLException: Represents database access errors.
■ ClassNotFoundException: Thrown when an application tries to load a
class at runtime but cannot find its definition.
○ Unchecked Exceptions: Also known as runtime exceptions, these do not need
to be declared or caught. They are checked at runtime.
■ RuntimeException: The superclass of all unchecked exceptions.
■ ArithmeticException: Thrown when an arithmetic operation fails,
such as division by zero.
■ NullPointerException: Thrown when the application attempts to
use null where an object is required.
■ ArrayIndexOutOfBoundsException: Thrown when an array is
accessed with an illegal index.

4. Exception Hierarchy Diagram

Here's a simplified diagram to illustrate the hierarchy:


3. Keywords throws and throw

Keywords throws and throw


In Java, exception handling is a crucial aspect of robust application development. The throws
and throw keywords are fundamental to handling exceptions in Java. Understanding how to
use these keywords correctly can help you manage errors effectively and ensure that your
application runs smoothly.
The throw Keyword

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:

public class ThrowExample {


public static void divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}
System.out.println("Result: " + (a / b));
}

public static void main(String[] args) {


try {
divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

Output:

Caught Exception: Division by zero is not allowed.



Explanation: In this example, the throw keyword is used to explicitly throw an
ArithmeticException when attempting to divide by zero.

The throws Keyword

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.*;

public class ThrowsExample {


public static void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
System.out.println(reader.readLine());
reader.close();
}

public static void main(String[] args) {


try {
readFile("nonexistentfile.txt");
} catch (IOException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

Output:

Caught Exception: nonexistentfile.txt (No such file or directory)



Explanation: In this example, the readFile method declares that it may throw an
IOException. The caller of this method (in main) must handle this exception using a try-
catch block.

Comparison and Use

When to Use throw


- Use throw when you want to manually throw an exception in a specific situation, often
when a condition arises that cannot be handled within the current method.
When to Use throws
- Use throws in a method declaration when you want to indicate that the method might
throw exceptions that need to be handled by the calling code.

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;

public class NumberFormatExceptionDemo {


public static void validateInteger(String input) {
try {
int number = Integer.parseInt(input);
System.out.println("Valid integer: " + number);
} catch (NumberFormatException e) {
throw new NumberFormatException("Invalid integer format: " + input);
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
String input = scanner.nextLine();
try {
validateInteger(input);
} catch (NumberFormatException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

Program 2: Using throws Write a Java program that declares a method readFile which
throws an IOException and handles the exception in the main method.

import java.io.*;

public class FileReadingDemo {


public static void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
System.out.println(reader.readLine());
reader.close();
}
public static void main(String[] args) {
try {
readFile("example.txt");
} catch (IOException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

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

2. What must a method do if it declares that it throws exceptions?

- A) Handle the exception within the method


- B) Declare the exception in its signature
- C) Call the method without handling the exception
- D) Propagate the exception to the caller

Answer: D) Propagate the exception to the caller


3. What is the correct syntax for declaring that a method might throw an
IOException?

- A) void methodName() throw IOException


- B) void methodName() throws IOException
- C) void methodName() throw new IOException
- D) void methodName() throws new IOException

Answer: B) void methodName() throws IOException

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

Answer: A) Compilation error

5. Which of the following is true about the throws keyword?

- A) It is used within a method to handle exceptions.


- B) It is used to declare that a method may throw exceptions.
- C) It is used to catch exceptions in the code.
- D) It is used to throw a specific exception.

Answer: B) It is used to declare that a method may throw exceptions.

4. try, catch, and finally Blocks

try, catch, and finally Blocks


Exception handling is a crucial concept in Java that helps in managing runtime errors gracefully.
The try, catch, and finally blocks are fundamental components of Java's exception
handling mechanism. This material provides a comprehensive overview of these blocks,
including syntax, examples, explanations, and practice exercises.
The try Block

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.

The catch Block

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.

The finally Block

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.*;

public class FinallyExample {


public static void main(String[] args) {
FileReader file = null;
try {
file = new FileReader("test.txt");
// Perform file operations
} catch (IOException e) {
System.out.println("Caught Exception: " + e.getMessage());
} finally {
try {
if (file != null) {
file.close();
}
} catch (IOException e) {
System.out.println("Failed to close file: " + e.getMessage());
}
}
}
}

Explanation: In this example, the finally block ensures that the file is closed regardless of
whether an exception occurs or not.

Practice Programs
Program 1: Nested Try-Catch-Finally Write a Java program that demonstrates the use of
nested try, catch, and finally blocks.

public class NestedTryExample {


public static void main(String[] args) {
try {
System.out.println("Outer try block");
try {
System.out.println("Inner try block");
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Inner catch block: " + e.getMessage());
} finally {
System.out.println("Inner finally block");
}
} catch (Exception e) {
System.out.println("Outer catch block: " + e.getMessage());
} finally {
System.out.println("Outer finally block");
}
}
}

Program 2: Using Finally Block for Resource Management Write a program that uses the
finally block to ensure a resource is always closed.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnectionExample {


public static void main(String[] args) {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:invalid:url"); // This will throw
SQLException
} catch (SQLException e) {
System.out.println("Caught SQLException: " + e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
System.out.println("Failed to close connection: " + e.getMessage());
}
}
}
}

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.

5. Define a custom exception class and use it within a try-catch-finally block in a


Java program.

Quiz
1. What will happen if an exception occurs in the try block?

- A) The finally block will not execute.


- B) The program will terminate immediately.
- C) Control will pass to the catch block if it exists.
- D) The catch block will execute, and then the finally block.

Answer: C) Control will pass to the catch block if it exists.

2. Which block will always execute, regardless of whether an exception occurs?

- A) catch
- B) try
- C) finally
- D) throw

Answer: C) finally

3. Can a finally block exist without a catch block?

- A) Yes
- B) No
- C) Only in Java 8 and later versions
- D) Only within a try-catch block

Answer: A) Yes

4. What happens if the finally block itself throws an exception?

- A) The finally block is ignored, and the program terminates.


- B) The exception is propagated, and the finally block's exception is handled
by the caller.
- C) The catch block handles the finally block's exception.
- D) The program will terminate without handling the exception.

Answer: B) The exception is propagated, and the finally block's exception is


handled by the caller.

5. Which of the following is true about the try block?

- A) It must be followed by a catch block.


- B) It must be followed by a finally block.
- C) It can be followed by one or more catch blocks and an optional finally
block.
- D) It can exist without a catch block or finally block.
Answer: C) It can be followed by one or more catch blocks and an optional
finally block.

5. Multiple Catch Clauses

Multiple Catch Clauses


In Java, you can handle multiple exceptions using multiple catch clauses. This approach
allows you to respond differently to different types of exceptions thrown by the try block. This
document provides a comprehensive overview of multiple catch clauses, including syntax,
examples, explanations, practice programs, homework questions, and multiple-choice
questions.

Introduction to Multiple Catch Clauses

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:

- ArrayIndexOutOfBoundsException is caught by the first catch block.


- If the first exception is not thrown, but an ArithmeticException is thrown, it is caught
by the second catch block.
- The third catch block will handle any other types of exceptions if they occur.

Handling Multiple Exceptions

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

int[] numbers = new int[5];


numbers[10] = 100; // ArrayIndexOutOfBoundsException
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " +
e.getMessage());
} catch (Exception e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

Explanation: Here, NullPointerException is handled first. If
ArrayIndexOutOfBoundsException occurs, it is caught by the second catch block. Any
other exceptions are caught by the last catch block.

Practice Programs
Program 1: Handling Multiple Exceptions

Write a Java program that handles NumberFormatException and


ArrayIndexOutOfBoundsException using multiple catch blocks.

public class NumberFormatExample {


public static void main(String[] args) {
try {
String str = "abc";
int num = Integer.parseInt(str); // NumberFormatException

int[] array = new int[3];


array[5] = 10; // ArrayIndexOutOfBoundsException
} catch (NumberFormatException e) {
System.out.println("Caught NumberFormatException: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " +
e.getMessage());
}
}
}

Program 2: Order of Catch Blocks

Create a program to show that catch blocks should be ordered from the most specific exception
type to the most general.

public class OrderOfCatchBlocks {


public static void main(String[] args) {
try {
int[] arr = new int[1];
arr[2] = 5; // ArrayIndexOutOfBoundsException
} catch (Exception e) {
System.out.println("Caught Exception: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " +
e.getMessage());
}
}
}

Program 3: Catching Multiple Exceptions with Common Handling

Demonstrate how to handle multiple exceptions with similar handling code.

public class CommonHandlingExample {


public static void main(String[] args) {
try {
int[] numbers = new int[5];
numbers[10] = 10; // ArrayIndexOutOfBoundsException
String str = null;
str.length(); // NullPointerException
} catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

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?

- A) Only the first catch block will execute.


- B) All catch blocks will execute.
- C) The catch blocks will be ignored.
- D) The first catch block that matches the exception will execute.

Answer: D) The first catch block that matches the exception will execute.

2. Which exception type should be caught first when handling exceptions?

- A) The most general exception


- B) The most specific exception
- C) Any exception type
- D) It does not matter

Answer: B) The most specific exception

3. Can a catch block handle more than one exception type?

- A) Yes, starting from Java 7.


- B) No, it can handle only one exception type.
- C) Yes, but only for checked exceptions.
- D) Yes, but only for unchecked exceptions.

Answer: A) Yes, starting from Java 7.

4. What will the following code output?

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

Answer: A) ArithmeticException caught

5. In the following code, which catch block will execute?

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

Answer: A) IOException caught

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.

Introduction to Throwable Class

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();

// Constructor that accepts a detail message


public Throwable(String message);

// Constructor that accepts a detail message and cause


public Throwable(String message, Throwable cause);

// Constructor that accepts a cause


public Throwable(Throwable cause);
}

Methods
Some of the key methods in the Throwable class are:

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


- String toString(): Returns a short description of this throwable.
- Throwable getCause(): Returns the cause of this throwable or null if the cause is
nonexistent or unknown.
- StackTraceElement[] getStackTrace(): Provides the stack trace information.
- void printStackTrace(): Prints the stack trace of this throwable to the standard
error stream.

Examples

Example 1: Basic Usage of Throwable


public class ThrowableExample {
public static void main(String[] args) {
try {
throw new Throwable("This is a throwable message");
} catch (Throwable t) {
System.out.println("Caught Throwable: " + t.getMessage());
t.printStackTrace();
}
}
}

Explanation: This example demonstrates how to throw and catch a Throwable. The message
is retrieved using getMessage(), and the stack trace is printed using printStackTrace().
Example 2: Custom Exception Using Throwable
public class CustomThrowable extends Throwable {
public CustomThrowable(String message) {
super(message);
}
}

public class CustomThrowableExample {


public static void main(String[] args) {
try {
throw new CustomThrowable("Custom Throwable Exception");
} catch (CustomThrowable e) {
System.out.println("Caught CustomThrowable: " + e.getMessage());
e.printStackTrace();
}
}
}

Explanation: This example creates a custom exception class that extends Throwable. The
custom exception is thrown and caught with specific handling.

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.

public class GenericThrowableHandling {


public static void main(String[] args) {
try {
throw new ArithmeticException("Arithmetic Exception");
} catch (Throwable t) {
System.out.println("Caught Throwable: " + t.getMessage());
t.printStackTrace();
}
}
}

Program 2: Exception with Cause Create a program where you throw a Throwable with a
cause and demonstrate how to retrieve and print the cause.

public class ThrowableWithCauseExample {


public static void main(String[] args) {
try {
Throwable cause = new Throwable("Root cause");
throw new Throwable("Exception with cause", cause);
} catch (Throwable t) {
System.out.println("Caught Throwable: " + t.getMessage());
System.out.println("Cause: " + t.getCause());
t.printStackTrace();
}
}
}

Program 3: Custom Exception with Stack Trace Define a custom exception that prints a
custom stack trace message.

public class CustomExceptionWithStackTrace extends Throwable {


public CustomExceptionWithStackTrace(String message) {
super(message);
}

@Override
public void printStackTrace() {
System.out.println("Custom stack trace message:");
super.printStackTrace();
}
}

public class CustomExceptionExample {


public static void main(String[] args) {
try {
throw new CustomExceptionWithStackTrace("Custom Exception");
} catch (CustomExceptionWithStackTrace e) {
e.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

2. Which method of Throwable provides the cause of the exception?

- A) getMessage()
- B) toString()
- C) getCause()
- D) printStackTrace()

Answer: C) getCause()

3. What will be the output of the following code?

try {
throw new Throwable("Exception Message");
} catch (Throwable t) {
System.out.println(t.getMessage());
}

- A) Exception Message
- B) Throwable
- C) null
- D) No output

Answer: A) Exception Message

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()

5. How can you create a custom exception that includes a cause?

- A) Extend Exception and use Throwable constructor with cause


- B) Extend Throwable and use Throwable constructor with cause
- C) Use Exception directly
- D) Use Error class with a custom method

Answer: B) Extend Throwable and use Throwable constructor with cause

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.

Introduction to Unchecked Exceptions

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

Common Unchecked Exceptions


- NullPointerException: Occurs when the application attempts to use null where
an object is required.
- ArrayIndexOutOfBoundsException: Thrown when an array is accessed with an
illegal index.
- ArithmeticException: Indicates errors in arithmetic operations, such as division by
zero.
- IllegalArgumentException: Thrown when a method receives an illegal or
inappropriate argument.

Syntax and Examples

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");
}
}

public static void main(String[] args) {


try {
validateAge(-5); // This line will throw IllegalArgumentException
} catch (IllegalArgumentException e) {
System.out.println("Caught IllegalArgumentException: " + e.getMessage());
}
}
}

Explanation: The IllegalArgumentException is used to indicate that a method has been
passed an inappropriate argument.
Practice Programs
Program 1: Handling Multiple Unchecked Exceptions Write a Java program that
demonstrates handling multiple unchecked exceptions (NullPointerException,
ArrayIndexOutOfBoundsException, ArithmeticException).

public class MultipleUncheckedExceptions {


public static void main(String[] args) {
try {
String str = null;
int length = str.length(); // NullPointerException

int[] array = new int[5];


int value = array[10]; // ArrayIndexOutOfBoundsException

int result = 10 / 0; // ArithmeticException


} catch (NullPointerException | ArrayIndexOutOfBoundsException |
ArithmeticException e) {
System.out.println("Caught Exception: " + e.getClass().getSimpleName() + "
- " + e.getMessage());
}
}
}

Program 2: Custom Unchecked Exception Create a custom unchecked exception that
extends RuntimeException and use it in a program.

public class CustomUncheckedException extends RuntimeException {


public CustomUncheckedException(String message) {
super(message);
}
}

public class CustomUncheckedExample {


public static void checkNumber(int number) {
if (number < 0) {
throw new CustomUncheckedException("Negative number not allowed");
}
}

public static void main(String[] args) {


try {
checkNumber(-10); // This will throw CustomUncheckedException
} catch (CustomUncheckedException e) {
System.out.println("Caught CustomUncheckedException: " + e.getMessage());
}
}
}

Program 3: Using Unchecked Exceptions for Validation Write a program that demonstrates
validation of input using unchecked exceptions.

public class InputValidationExample {


public static void validateInput(int value) {
if (value < 1 || value > 100) {
throw new IllegalArgumentException("Input must be between 1 and 100");
}
}

public static void main(String[] args) {


try {
validateInput(150); // This will throw IllegalArgumentException
} catch (IllegalArgumentException e) {
System.out.println("Caught IllegalArgumentException: " + e.getMessage());
}
}
}

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

2. What type of exception is ArrayIndexOutOfBoundsException?

- A) Checked Exception
- B) Unchecked Exception
- C) Error
- D) RuntimeException

Answer: B) Unchecked Exception

3. What will be the output of the following code?

public class Example {


public static void main(String[] args) {
try {
int[] arr = new int[2];
arr[3] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e.getClass().getSimpleName());
}
}
}

- A) Exception caught: ArrayIndexOutOfBoundsException
- B) Exception caught: IndexOutOfBoundsException
- C) No output
- D) Exception caught: ArrayIndexOutOfBoundsException,
IndexOutOfBoundsException

Answer: A) Exception caught: ArrayIndexOutOfBoundsException

4. How can you avoid a NullPointerException?

- A) By checking for null before using an object


- B) By catching the exception using a try-catch block
- C) By using a custom exception
- D) By setting a default value

Answer: A) By checking for null before using an object

5. What will be the output of the following code?

public class Test {


public static void main(String[] args) {
int number = 0;
int result = 1 / number; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Exception: " + e.getClass().getSimpleName());
}
}

- A) Exception: ArithmeticException
- B) Exception: Exception
- C) No output
- D) Exception: RuntimeException

Answer: A) Exception: ArithmeticException

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.

Introduction to Checked Exceptions

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.

Syntax and Examples

Example 1: Handling IOException


import java.io.FileReader;
import java.io.IOException;

public class IOExceptionExample {


public static void main(String[] args) {
try {
FileReader file = new FileReader("nonexistentfile.txt"); // This line will
throw IOException
file.close();
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
}
}
}

Explanation: IOException is thrown when trying to open a file that does not exist. The
exception is caught and handled in the catch block.

Example 2: Handling SQLException


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class SQLExceptionExample {


public static void main(String[] args) {
try {
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username",
"password"); // This line may throw SQLException
conn.close();
} catch (SQLException e) {
System.out.println("Caught SQLException: " + e.getMessage());
}
}
}

Explanation: SQLException is thrown when a database connection fails. The exception is
handled in the catch block.

Example 3: Declaring and Handling ClassNotFoundException


public class ClassNotFoundExceptionExample {
public static void loadClass() throws ClassNotFoundException {
Class.forName("com.example.NonExistentClass"); // This line will throw
ClassNotFoundException
}

public static void main(String[] args) {


try {
loadClass();
} catch (ClassNotFoundException e) {
System.out.println("Caught ClassNotFoundException: " + e.getMessage());
}
}
}

Explanation: ClassNotFoundException is thrown when trying to load a class that does not
exist. The method loadClass() declares that it throws this exception, which is handled in the
main method.

Example 4: Custom Checked Exception


class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

public class CustomCheckedExceptionExample {


public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older");
}
}

public static void main(String[] args) {


try {
validateAge(16); // This will throw InvalidAgeException
} catch (InvalidAgeException e) {
System.out.println("Caught InvalidAgeException: " + e.getMessage());
}
}
}

Explanation: A custom checked exception InvalidAgeException is created and thrown if
an invalid age is provided. This exception is declared to be thrown and handled in the main
method.

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;

public class MultipleCheckedExceptions {


public static void main(String[] args) {
try {
FileReader file = new FileReader("file.txt");
file.close();

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.

public class ExceptionPropagation {


public static void methodA() throws ClassNotFoundException {
Class.forName("com.example.NonExistentClass"); // This will throw
ClassNotFoundException
}
public static void methodB() throws ClassNotFoundException {
methodA(); // Exception is propagated from methodA to methodB
}

public static void main(String[] args) {


try {
methodB();
} catch (ClassNotFoundException e) {
System.out.println("Caught ClassNotFoundException: " + e.getMessage());
}
}
}

Program 3: Creating and Throwing a Custom Exception Write a program that creates and
throws a custom checked exception based on certain conditions.

class AgeNotValidException extends Exception {


public AgeNotValidException(String message) {
super(message);
}
}

public class ValidateAge {


public static void checkAge(int age) throws AgeNotValidException {
if (age < 18) {
throw new AgeNotValidException("Age is not valid for this operation");
}
}

public static void main(String[] args) {


try {
checkAge(15); // This will throw AgeNotValidException
} catch (AgeNotValidException e) {
System.out.println("Caught AgeNotValidException: " + e.getMessage());
}
}
}

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

2. What must a method do if it declares that it throws a checked exception?

- A) Catch the exception


- B) Declare it again in the method signature
- C) Propagate it to the calling method
- D) Handle it with a try-catch block

Answer: C) Propagate it to the calling method

3. What is the output of the following code if the file does not exist?

import java.io.FileReader;
import java.io.IOException;

public class Test {


public static void main(String[] args) {
try {
FileReader file = new FileReader("file.txt");
file.close();
} catch (IOException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}

- A) No output
- B) Exception: file.txt (The system cannot find the file specified)
- C) Exception: IOException
- D) Exception: FileNotFoundException

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

5. What is the purpose of declaring a checked exception in a method signature?

- A) To handle the exception within the method


- B) To inform the compiler that the method may throw this exception
- C) To automatically handle the exception
- D) To log the exception

Answer: B) To inform the compiler that the method may throw this exception

References

End of Session - 24

You might also like