Exception Handling in Java
Exception Handling in Java
T
● hese are exceptions checked at compile-time.
● Examples:
○
IOException
○ SQLException
xample:
E
Java code
import java.io.*;
T
● hese occur during runtime and are not checked at compile-time.
● Examples:
○
ArithmeticException
○NullPointerException
○ ArrayIndexOutOfBoundsException
xample:
E
Java code
public class UncheckedExceptionExample {
public static void main(String[] args) {
int num = 10 / 0; // Causes ArithmeticException
}
}
(c) Errors
E
● rrors are serious issues that the application cannot recover from.
● Examples:
○
StackOverflowError
○ OutOfMemoryError
● Root:
Throwable
○ Error: Irrecoverable issues (e.g., JVM errors).
○ Exception: Recoverable conditions:
■ Checked exceptions ( IOException ,
SQLException).
■ Unchecked exceptions (
ArithmeticException,
NullPointerException).
xample:
E
Java code
public class TryCatchExample {
public static void main(String[] args) {
try {
int num = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
A
● lways executes whether an exception occurs or not.
● Used for cleanup operations like closing files or database connections.
xample:
E
Java code
public class FinallyExample {
public static void main(String[] args) {
try {
int num = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());
} finally {
System.out.println("This block always executes.");
}
}
}
(a) Throw
yntax:
S
Java code
throw new ExceptionType("Exception message");
xample:
E
Java code
public class ThrowExample {
public static void main(String[] args) {
validateAge(15);
}
static void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or
above");
}
System.out.println("Valid age");
}
}
(b) Throws
● Used in method signatures to declare exceptions that the method might throw.
yntax:
S
Java code
returnType methodName() throws ExceptionType1, ExceptionType2 {
// Method code
}
xample:
E
Java code
import java.io.*;
W
● e can create user-defined exceptions by extending the
Exceptionclass.
● Steps:
1. Extend the Exceptionclass (or
RuntimeExceptionforunchecked
exceptions).
2. Provide a constructor for custom messages.
xample:
E
Java code
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
A
●
tryblock can be followed by multiple
catchblocksto handle different exceptions.
● Rule: More specific exceptions should come beforemore general ones.
xample:
E
Java code
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int arr[] = new int[5];
arr[5] = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " +
e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException
caught: " + e.getMessage());
}
}
}
xample:
E
Java code
import java.io.*;
● Exceptions are propagated from one method to another unless handled explicitly.
xample:
E
Java code
public class ExceptionPropagationExample {
public static void main(String[] args) {
try {
method1();
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());
}
}
umber of
N an throw only one exception
C an declare multiple exceptions
C
Exceptions at a time. separated by commas.
xample:
E
Java code
public class FinallyExample {
public static void main(String[] args) {
try {
int num = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
}
Output:
aught: / by zero
C
Finally block executed.
Keyword/Method Purpose
final
keyword used to declare constants, prevent method overriding, or
A
prevent inheritance.
finally
A block used for cleanup operations in exception handling.
finalize()
method invoked by the garbage collector before an object is
A
destroyed (deprecated in Java 9).
xample:
E
Java code
public class FinallyExceptionExample {
public static void main(String[] args) {
try {
throw new ArithmeticException("Exception from try");
} finally {
throw new NullPointerException("Exception from
finally");
}
}
}
Output:
xample:
E
Java code
public class TryWithoutCatchExample {
public static void main(String[] args) {
try {
System.out.println("Try block executed");
} finally {
System.out.println("Finally block executed");
}
}
}
Output:
● E ach thread has its owncall stack, and exceptions must be handled within the
thread itself.
● If an exception occurs in one thread, it doesn't affect other threads.
xample:
E
Java code
public class MultiThreadExceptionExample extends Thread {
public void run() {
try {
System.out.println("Thread running: " +
Thread.currentThread().getName());
int num = 10 / 0; // Causes ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Exception caught in thread: " +
Thread.currentThread().getName());
}
}