You are on page 1of 6

Experiment 07: Exception Handling In Java Learning

Objectives: To understand Exception Handling in java

Theory:
Exception handling in Java is crucial for writing robust and reliable code. The basic theory behind
exception handling in Java revolves around the concept of handling unexpected situations, known as
exceptions, that may occur during program execution. Here's a breakdown of the theory behind
exception handling in Java:
Exception: An exception is an event that disrupts the normal flow of the program's instructions during
execution. Exceptions can occur due to various reasons such as invalid user input, hardware failure,
network issues, etc.
Exception Handling Mechanism: Java provides a built-in exception handling mechanism to deal with
exceptions effectively. The core components of Java's exception handling mechanism include:
try-catch blocks: The try block encloses the code that might throw an exception. If an exception
occurs within the try block, it is caught by one or more catch blocks that match the type of exception
thrown. try {
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Handle exception of type ExceptionType1
} catch (ExceptionType2 e2) {
// Handle exception of type ExceptionType2
} finally {
// Optional cleanup code that always executes
} catch blocks: These blocks handle exceptions. They contain the code that executes when a
specific
type of exception occurs. You can have multiple catch blocks to handle different types of exceptions.
finally block: This block is optional and follows the try-catch block. It contains code that always
executes, regardless of whether an exception occurs or not. Commonly used for cleanup tasks like
closing resources.
Exception Class Hierarchy: In Java, exceptions are represented as objects belonging to classes that
extend either directly or indirectly from the Throwable class. There are two main types of exceptions:
checked exceptions and unchecked exceptions.
Checked Exceptions: These are exceptions that are checked at compile-time. They extend Exception
class (or its subclasses), excluding RuntimeException and its subclasses. Examples include
IOException, SQLException, etc.
Unchecked Exceptions: Also known as runtime exceptions, these exceptions are not checked at
compile-time. They extend RuntimeException or its subclasses. Examples include
NullPointerException, ArrayIndexOutOfBoundsException, etc.
Throwing Exceptions: In Java, you can explicitly throw exceptions using the throw keyword. This
allows you to create and throw custom exceptions or propagate existing exceptions.
Custom Exceptions: Java allows you to define custom exception classes by extending either Exception
or RuntimeException. Custom exceptions are useful for representing specific error conditions in your
application.
Advantage of Exception Handling: Exception handling in Java enhances code readability,
promotes modularity, improves debugging with detailed error messages, supports graceful error
recovery, ensures program robustness by preventing abrupt terminations, enables encapsulation of
error-handling logic for reuse, and facilitates better separation of concerns between regular and
error-handling code.

Problem Statement 1: Write a java program to implement try and catch in bufferReader.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BufferedReaderTryCatch {


public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

try {
System.out.print("Enter a number: ");
String input = reader.readLine();
int number = Integer.parseInt(input);
System.out.println("You entered: " + number);
} catch (IOException e) {
System.err.println("Error reading input: " + e.getMessage());
} catch (NumberFormatException e) {
System.err.println("Invalid input format: " + e.getMessage());
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
System.err.println("Error closing BufferedReader: " + e.getMessage());
}
}
}
}

Problem Statement 2: Write a java program to show the implementation of vector in java Program:
// Define an interface
interface Animal {
void makeSound();
}

// Implement the interface


class Dog implements Animal {
public void makeSound() {
System.out.println("Woof");
}
}

class Cat implements Animal {


public void makeSound() {
System.out.println("Meow");
}
}

public class Main {


public static void main(String[] args) {
// Create objects of classes implementing the interface
Dog dog = new Dog();
Cat cat = new Cat();

// Call the method defined in the interface


dog.makeSound();
cat.makeSound();
}
}

Output:
Learning Outcomes: Student will be able to
LO1.1 Understand the use of try and catch method
LO1.2 Understand the vector implementation Course
Outcome:
Student will be able to implement the try and catch method and can handle exception in the program.
Conclusion
In conclusion, exception handling in Java is pivotal for maintaining robust and readable code. It
enables graceful error recovery, enhances debugging with detailed error messages, and prevents
abrupt program terminations. Additionally, it promotes modularity and encapsulation of error-
handling logic, fostering better code organization and reuse.

Viva Questions:
• What is the purpose of the finally block in Java exception handling?
Ans: The finally block in Java exception handling is used to define code that should execute
regardless of whether an exception is thrown or not. It is typically employed to perform
cleanup tasks, such as closing resources like files or database connections, ensuring that
critical resources are released properly, even if an exception occurs within the try block. This
ensures that resources are not left in an inconsistent or unreleased state, contributing to the
robustness and reliability of the program.
• What is the main difference between `Vector` and `ArrayList` in Java?
Ans: The primary difference is that `Vector` is synchronized, meaning it's thread-safe, while
`ArrayList` is not. This makes `Vector` slower in single-threaded environments but safer in
multithreaded ones.

For Faculty Use only:

Correction Formative Timely completion Attendance / Total


Parameters Assessment of Practical [ 40%] Learning
[40%] Attitude [20%]
Marks
Obtained

You might also like