Exceptions in Java are events that disrupt the normal flow of a program's execution. They are used to handle errors and other exceptional events that may occur during runtime.
Types of Exceptions
-
Checked Exceptions (compile-time exceptions)
- Must be declared or handled (using try-catch or throws)
- Examples:
IOException
,SQLException
,ClassNotFoundException
-
Unchecked Exceptions (runtime exceptions)
- Not checked at compile time
- Examples:
NullPointerException
,ArrayIndexOutOfBoundsException
,ArithmeticException
-
Errors
- Serious problems that applications should not try to catch
- Examples:
OutOfMemoryError
,StackOverflowError
Exception Handling Keywords
-
try
: Block of code to monitor for exceptions -
catch
: Block that handles the exception -
finally
: Block that always executes (for cleanup) -
throw
: Used to explicitly throw an exception -
throws
: Declares exceptions that might be thrown by a method
Example
try {
// Code that might throw an exception
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} catch (Exception e) {
System.out.println("General exception caught");
} finally {
System.out.println("This will always execute");
}
Custom Exceptions
You can create your own exception classes by extending Exception
(checked) or RuntimeException
(unchecked):
class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
Best Practices
- Catch specific exceptions rather than general Exception
- Don't ignore caught exceptions (empty catch blocks)
- Use finally blocks for resource cleanup
- Document exceptions with @throws in JavaDoc
- Consider whether to handle, propagate, or convert exceptions
Would you like more details on any specific aspect of Java exceptions?