BCA COLLEGE IDAR
[Link] Meman
1. Exception Handling in Java
Exception: An exception is an unwanted event that disrupts the normal flow of a program.
Exception Handling: A mechanism to handle runtime errors so that normal execution of the
program can continue
Types of Exceptions
1. Checked Exceptions
o Checked at compile-time.
o Must be handled using try-catch or declared using throws.
o Example: IOException, SQLException.
2. Unchecked Exceptions
o Occur at runtime.
o Not checked by compiler.
o Example: ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException.
Java Exception Handling Keywords
try → block of code to test for exceptions.
catch → block to handle exception.
finally → block that always executes (cleanup code).
throw → used to throw an exception object explicitly.
throws → declares exceptions that a method can throw.
Other Concepts
Nested try: A try block inside another try block.
Multiple catch: Multiple catch blocks for different exception types.
User-defined Exception: Custom exception class created by extending Exception or
RuntimeException.
Example:
Try
{
int a = 10/0;
}
catch(ArithmeticException e)
{
[Link]("Divide by zero error!");
}
finally
{
[Link]("This block always executes.");
}