? Java Exceptions
? Quick Overview
Exceptions in Java represent abnormal conditions that interrupt the normal flow of a program. Java provides a powerful exception-handling mechanism using predefined classes and keywords.
? Key Concepts
- Exception is an object that represents an error
- All exceptions inherit from
Throwable
- Handled using
try, catch, finally
- Can be checked or unchecked
? Syntax / Theory
Java exceptions are broadly classified into:
- Checked Exceptions – Checked at compile time
- Unchecked Exceptions – Occur at runtime
- Errors – Serious issues not meant to be handled
? Code Example
? View Code Example
public class ExceptionDemo {
public static void main(String[] args) {
int a = 10;
int b = 0;
System.out.println(a / b);
}
}
?️ Live Output / Explanation
Output
Exception in thread "main" java.lang.ArithmeticException: / by zero
The program crashes because division by zero is not allowed.
? Common Types of Java Exceptions
- ArithmeticException – Thrown when an exceptional arithmetic condition occurs (e.g., integer division by zero).
- NullPointerException – Thrown when an application attempts to use
null in a case where an object is required.
- ArrayIndexOutOfBoundsException – Thrown when trying to access an array with an illegal index (negative or outside the size).
- StringIndexOutOfBoundsException – Thrown by String methods to indicate that an index is either negative or greater than the size of the string.
- NumberFormatException – Thrown when attempting to convert a string (like "abc") into a numeric type (like
int) but the format is invalid.
- ClassNotFoundException – Thrown when an application tries to load a class through its string name, but the class cannot be found.
- IOException – Signals that an Input/Output exception of some sort has occurred (e.g., reading/writing errors).
- SQLException – An exception that provides information on a database access error or other errors related to SQL.
- FileNotFoundException – Signals that an attempt to open a file denoted by a specified pathname has failed because the file does not exist.
- InterruptedException – Thrown when a thread is waiting or sleeping and is interrupted by another thread.
? Tips & Best Practices
- Always handle checked exceptions
- Use specific exceptions instead of generic ones
- Avoid empty catch blocks
- Use finally for cleanup code
? Try It Yourself
- Write a program that handles NullPointerException
- Create a custom exception class
- Use multiple catch blocks