Chapter 4-Exceptional Handling
✓Definition of Exception
✓Importance of Exception Handling
✓Overview of Exception Types (Checked, Unchecked, Errors)
Exceptional Handling…
✓Exception is a run-time error which arises during the execution of java
program.
✓The term exception in java stands for an exceptional event.
✓It can be defined as abnormal event that arises during the execution and
normal flow of program.
✓An exception is an event, which occurs during the execution of programs
that disturbs the normal flow of the program's instructions.
What is an Exception?
▪ Exceptions can occur due to various reasons such as invalid data input, file not
found, memory allocation errors, or network connectivity issues.
▪ When an error occurs within a method, the method creates an exception object
containing information about the error, including its type and the state of the
program when the error occurred.
▪ Exception handling in Java involves identifying, managing, and responding to these
runtime errors to ensure smooth program execution.
Role of Exception in Java
▪ Enabling systematic handling of error conditions.
▪ Facilitating graceful recovery from unexpected runtime errors.
▪ Improving program reliability and robustness.
▪ Allowing developers to manage and respond to runtime errors
effectively.
▪ Preventing abrupt termination of programs by providing mechanisms
for error handling and resolution.
Most Common Exception in Java
▪ ArithmeticException: Occurs when arithmetic operations such as
division by zero are attempted.
▪ FileNotFoundException: Occurs when a file specified for reading or
writing does not exist.
▪ NullPointerException: Occurs when attempting to access or
manipulate objects with a null reference.
▪ ArrayIndexOutOfBoundsException: Occurs when trying to access an
array element with an invalid index.
Additional Exceptions in Java
•IllegalArgumentException: Arises when an illegal argument is used to
invoke a method.
•IOException: Denotes input/output errors, such as when reading from or
writing to files.
•NumberFormatException: Occurs when an invalid conversion of a
string to a numeric format is attempted.
Throwable Class and Subclasses
✓ Throwable Class: The Throwable class serves as the root of the Java exception class
hierarchy.
✓ It defines objects that can be thrown and caught.
Throwable Class Hierarchy:
✓ Throwable
▪ Error
▪ Exception
o Checked Exceptions by the compiler-IOException and SQLException
o Unchecked Exceptions-RuntimeException(FileNOTFound,
ArrayOutOfBoundException…)
Error Class Definition and Usage
Error Class: Errors in Java represent serious, often irrecoverable problems that occur
beyond the control of the programmer.
✓ Typically, errors are not caught or handled within the program but are allowed to
propagate to the top-level error handler.
Usage: Examples of Errors: OutOfMemoryError, StackOverflowError,
VirtualMachineError.
✓ Simple programs usually do not catch or throw Errors.
✓ Errors indicate critical system failures or resource depletion, requiring intervention at
a higher level.
Exception Class Definition and Usage
Exception Class:
▪ Exceptions in Java represent exceptional conditions that can occur during the
execution of a program, but they are not necessarily fatal.
Usage:
▪ Exceptions are typically caught and handled within the program to recover from
exceptional conditions and maintain program stability.
▪ The Exception class is further subclassed to represent various types of exceptions.
▪ Most programs handle and throw objects derived from the Exception class.
Exception Handling Mechanisms
✓Exception handling in Java is a programming construct that enables the
systematic management of runtime errors or exceptional conditions.
✓It allows developers to anticipate, detect, and respond to exceptional
scenarios, ensuring smooth program execution.
Components of Exceptional Handling
1. try: Encloses the code block where exceptions may occur.
2. catch: Catches and handles specific types of exceptions.
3. throw: Explicitly throws an exception to indicate an exceptional
condition.
4. throws: Declares that a method may throw a particular type of
exception.
5. finally: Defines a block of code that always executes, regardless of
whether an exception occurs.
Example
Output???
Example
The output of the program given before this slide is:
throws
▪ To declare checked exceptions that can be thrown by the method.
▪ When the method itself does not handle the exceptions but wants to
indicate to the caller that certain exceptions may occur.
▪ When the method relies on external resources or dependencies that may
cause exceptions.
public void readFile(String filename) throws FileNotFoundException {
FileReader fileReader = new FileReader(filename);
// Read file contents
}
throw
throw Usage Scenarios: To manually throw an exception when a specific
condition is met within a method.
✓When validating input parameters or performing custom error checking.
✓When handling exceptional conditions that cannot be handled locally.
public void validateAge(int age) {
if (age < 0 || age > 120) {
throw new IllegalArgumentException("Invalid age: " + age);
}
}
Making Errors With Out Exceptional handling
Since there's no exception handling mechanism in place, the program terminates abruptly, and the
exception message is printed to the console.
Making Errors With Exceptional handling
Handling Argument Exception
▪ To handle argument exceptions in Java, you can use various techniques
such as input validation or try-catch blocks.
The Importance of Proper Structure
1. Ensures Proper Error Handling: Properly structured exception handling blocks ensure that errors are
handled appropriately, preventing program crashes and unexpected behavior.
2. Maintains Code Readability: Organized and structured exception handling blocks improve code
readability and make it easier to understand how errors are handled within the program.
3. Facilitates Debugging: A well-structured exception handling structure aids in debugging by clearly
indicating where and how exceptions are caught and handled.
4. Prevents Resource Leaks: The finally block ensures that resources are properly released, preventing
resource leaks even in the event of an exception.
5. Promotes Robustness: By following the rules for exception handling blocks, programs become more
robust and resilient to unexpected errors, enhancing overall software quality.
Thank You!