📌 WHAT IS AN EXCEPTION?
An exception is an event that disrupts the normal flow of a
program.
It usually occurs when something unexpected happens during
execution — such as:
Dividing by zero
Accessing an invalid array index
Opening a file that doesn’t exist
Invalid input from the user
⚙️EXCEPTION HANDLING FUNDAMENTALS
Exception handling is a mechanism in Java used to detect
errors, handle them, and prevent the program from crashing.
Java exception handling is managed via five keywords: try,
catch,throw, throws, and finally.
Try Catch Throw Throws Finally
File Edit Selection View Go Run Terminal Help
Demo
🧠 General Structure of Exception Handling
try {
// Code to monitor for errors
}
catch (ExceptionType ex) {
// Code to handle the error
}
finally {
// Code that always runs (optional)
}
📌 FLOW OF EXCEPTION HANDLING
1 Program statements that we want to monitor for exceptions are
contained within a try block.
2 If an exception occurs within the try block, it is thrown.
3 Our code can catch this exception (using catch) and handle it in some
rational manner.
4 System-generated exceptions are automatically thrown by the Java
run time system.
5 To manually throw an exception, we use the keyword throw. Any
exception that is thrown out of a method must be specified as such by
a throws clause.
6 Any code that must be executed after a try block completes is
put in a finally block.
File Edit Selection View Go Run Terminal Help
Demo
Simple Example
public class Example {
public static void main(String[] args) {
try {
int result = 10 / 0; // Exception occurs here
}
catch (ArithmeticException e) {
[Link]("You cannot divide by zero.");
}
finally {
[Link]("This always executes.");
}
}
}
OUTPUT:
You cannot divide by zero.
This always executes.
🔍 WHY IS EXCEPTION HANDLING IMPORTANT?
Prevents program crashes
Improves reliability
Helps debug problems
Provides controlled error messages
Useful for input validation, file handling,
database access, etc.
THANK
YOU