0% found this document useful (0 votes)
3 views4 pages

Exception Handling

This document is a comprehensive cheatsheet on Java Exception Handling, covering key concepts such as the exception hierarchy, try-catch blocks, throwing exceptions, and custom exceptions. It also includes best practices for exception handling, common runtime exceptions, and various exception handling patterns. Additionally, it provides guidelines for effective exception management and performance considerations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views4 pages

Exception Handling

This document is a comprehensive cheatsheet on Java Exception Handling, covering key concepts such as the exception hierarchy, try-catch blocks, throwing exceptions, and custom exceptions. It also includes best practices for exception handling, common runtime exceptions, and various exception handling patterns. Additionally, it provides guidelines for effective exception management and performance considerations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Java Exception Handling Cheatsheet

1 Exception Hierarchy 3 Finally Block


Throwable F il eI np u tS tr ea m fis = null ;
try {
Error (unchecked): OutOfMemoryError, StackOverflowError
fis = new F il eI np u tS tr ea m ( " file . txt " ) ;
Exception // read file
RuntimeException (unchecked) } catch ( IOException e ) {
NullPointerException System . out . println ( " File error : " + e . getMessage () ) ;
} finally {
ArrayIndexOutOfBoundsException // Always executed ( even if exception occurs )
IllegalArgumentException if ( fis != null ) {
NumberFormatException try {
Checked Exceptions fis . close () ;
} catch ( IOException e ) {
IOException System . out . println ( " Error closing file " ) ;
SQLException }
ClassNotFoundException }
}
2 Basic Try-Catch
4 Try-With-Resources (Java 7+)
2.1 Simple Try-Catch
4.1 Single Resource
try {
int result = 10 / 0; // risky operation try ( F il e In pu tS t re am fis = new F il eI n pu tS tr e am ( " file . txt " ) ) {
System . out . println ( result ) ; // use file
} catch ( A r i t h m e t i c E x c e p t i o n e ) { // fis . close () called automatically
System . out . println ( " Division by zero : " + e . getMessage () ) ; } catch ( IOException e ) {
} System . out . println ( " File error : " + e . getMessage () ) ;
}

2.2 Multiple Catch Blocks 4.2 Multiple Resources


try { try ( F il e In pu tS t re am fis = new F il eI n pu tS tr e am ( " input . txt " ) ;
String str = null ; F i l e O u t p u t S t r e a m fos = new F i l e O u t p u t S t r e a m ( " output . txt " ) ;
int length = str . length () ; // N u l l P o i n t e r E x c e p t i o n Buff eredRead er br = new B ufferedR eader ( new FileReader ( " data . txt " ) ) ) {
int [] arr = {1 , 2 , 3};
int value = arr [5]; // A r r a y I n d e x O u t O f B o u n d s E x c e p t i o n // use resources
} catch ( N u l l P o i n t e r E x c e p t i o n e ) { // All resources closed automatically in reverse order
System . out . println ( " Null pointer : " + e . getMessage () ) ;
} catch ( A r r a y I n d e x O u t O f B o u n d s E x c e p t i o n e ) { } catch ( IOException e ) {
System . out . println ( " Array index : " + e . getMessage () ) ; System . out . println ( " I / O error : " + e . getMessage () ) ;
} catch ( Exception e ) { // catch - all ( should be last ) }
System . out . println ( " General exception : " + e . getMessage () ) ;
}
4.3 Enhanced Try-With-Resources (Java 9+)
2.3 Multi-Catch (Java 7+) F il eI np u tS tr ea m fis = new Fi le I np ut St r ea m ( " file . txt " ) ;
F i l e O u t p u t S t r e am fos = new F i l e O u t p u t S t r e am ( " output . txt " ) ;
try {
// risky operations try ( fis ; fos ) { // can reference existing variables
} catch ( IOException | SQLException e ) { // use resources
System . out . println ( " I / O or SQL error : " + e . getMessage () ) ; } catch ( IOException e ) {
// Note : e is effectively final System . out . println ( " I / O error : " + e . getMessage () ) ;
} }

1
5 Throwing Exceptions // Usage
public void withdraw ( double amount ) throws I n s u f f i c i e n t F u n d s E x c e p t i o n {
5.1 Throw Statement if ( amount > balance ) {
throw new I n s u f f i c i e n t F u n d s E x c e p t i o n (
public void validateAge ( int age ) { " Insufficient funds . Available : " + balance , amount ) ;
if ( age < 0) { }
throw new I l l e g a l A r g u m e n t E x c e p t i o n ( " Age cannot be negative " ) ; balance -= amount ;
} }
if ( age > 150) {
throw new I l l e g a l A r g u m e n t E x c e p t i o n ( " Age too high : " + age ) ;
}
6.2 Custom Unchecked Exception
} public class I n v a l i d C o n f i g u r a t i o n E x c e p t i o n extends R u n t i m e E x c e p t i o n {
public I n v a l i d C o n f i g u r a t i o n E x c e p t i o n ( String message ) {
public void processFile ( String filename ) { super ( message ) ;
if ( filename == null || filename . isEmpty () ) { }
throw new N u l l P o i n t e r E x c e p t i o n ( " Filename cannot be null / empty " ) ;
} public I n v a l i d C o n f i g u r a t i o n E x c e p t i o n ( String message , Throwable cause )
} {
super ( message , cause ) ;
5.2 Throws Declaration }
}
// Method declares it might throw checked exceptions
public void readFile ( String filename ) throws IOException { // Usage ( no throws declaration needed )
FileReader fr = new FileReader ( filename ) ; // might throw IOException public void loadConfig ( String config ) {
// process file if ( config == null ) {
} throw new I n v a l i d C o n f i g u r a t i o n E x c e p t i o n ( " Config cannot be null " ) ;
}
public void connectDB () throws SQLException , C l a s s N o t F o u n d E x c e p t i o n { }
Class . forName ( " com . mysql . jdbc . Driver " ) ; // C l a s s N o t F o u n d E x c e p t i o n
DriverManager . getConnection ( " jdbc : mysql :// localhost / db " ) ; //
SQLException 7 Exception Information
}
7.1 Exception Methods
// Multiple exceptions
public void riskyMethod () throws IOException , SQLException { try {
// method implementati on // risky operation
} } catch ( Exception e ) {
String message = e . getMessage () ; // error message
String className = e . getClass () . getName () ; // exception class
6 Custom Exceptions S t a c k T r a c e E l e m e n t [] stack = e . getStackTrace () ; // stack trace
Throwable cause = e . getCause () ; // root cause
6.1 Custom Checked Exception
e . pr i nt St ac k Tr ac e () ; // print to System . err
public class I n s u f f i c i e n t F u n d s E x c e p t i o n extends Exception { e . pr i nt St ac k Tr ac e ( System . out ) ; // print to specific stream
private double amount ;
// Convert to string
public I n s u f f i c i e n t F u n d s E x c e p t i o n ( String message , double amount ) { StringWriter sw = new StringWriter () ;
super ( message ) ; PrintWriter pw = new PrintWriter ( sw ) ;
this . amount = amount ; e . pr i nt St ac k Tr ac e ( pw ) ;
} String stackTrace = sw . toString () ;
}
public double getAmount () {
return amount ; 7.2 Chained Exceptions
}
} public void processData () throws D a t a P r o c e s s i n g E x c e p t i o n {
try {

2
// database operation logger . error ( " Failed to connect to database " , e ) ;
connection . executeQuery ( " SELECT * FROM users " ) ; throw e ; // re - throw after logging
} catch ( SQLException e ) { }
// Wrap and rethrow with more context }
throw new D a t a P r o c e s s i n g E x c e p t i o n ( " Failed to process user data " , e
); public void close () {
} if ( connection != null ) {
} try {
connection . close () ;
// Custom exception with chaining } catch ( SQLException e ) {
public class D a t a P r o c e s s i n g E x c e p t i o n extends Exception { logger . warn ( " Error closing connection " , e ) ;
public D a t a P r o c e s s i n g E x c e p t i o n ( String message , Throwable cause ) { // Don ’t re - throw in cleanup methods
super ( message , cause ) ; }
} }
} }
}

8 Common Runtime Exceptions


9.2 Retry Pattern
// N u l l P o i n t e r E x c e p t i o n public void c o n n e c t W i t h R e t r y ( int maxAttempts ) {
String str = null ; int attempts = 0;
int length = str . length () ; // NPE while ( attempts < maxAttempts ) {
try {
// A r r a y I n d e x O u t O f B o u n d s E x c e p t i o n connect () ;
int [] arr = {1 , 2 , 3}; return ; // success
int value = arr [5]; // AIOOBE } catch ( C o n n e c t i o n E x c e p t i o n e ) {
attempts ++;
// N u m b e r F o r m a t E x c e p t i o n if ( attempts >= maxAttempts ) {
int num = Integer . parseInt ( " abc " ) ; // NFE throw new C o n n e c t i o n E x c e p t i o n ( " Failed after " +
maxAttempts + " attempts " , e ) ;
// I l l e g a l A r g u m e n t E x c e p t i o n }
Thread . sleep ( -1000) ; // IAE try {
Thread . sleep (1000 * attempts ) ; // exponential backoff
// C l a s s C a s t E x c e p t i o n } catch ( I n t e r r u p t e d E x c e p t i o n ie ) {
Object obj = " Hello " ; Thread . currentThread () . interrupt () ;
Integer num = ( Integer ) obj ; // CCE throw new R u n t i m e E x c e p t i o n ( " Interrupted during retry " , ie )
;
// A r i t h m e t i c E x c e p t i o n }
int result = 10 / 0; // AE }
}
// S t r i n g I n d e x O u t O f B o u n d s E x c e p t i o n }
String str = " Hello " ;
char ch = str . charAt (10) ; // SIOOBE
9.3 Fallback Pattern
9 Exception Handling Patterns public String getConf igValue ( String key ) {
try {
9.1 Resource Management Pattern return l o a d F r o mD a t a b a s e ( key ) ;
} catch ( D a t a b a s e E x c e p t i o n e ) {
public class Da t ab as e Ma na ge r { logger . warn ( " Database unavailable , using file config " , e ) ;
private Connection connection ; try {
return loadFromFile ( key ) ;
public void connect () throws SQLException { } catch ( IOException e2 ) {
try { logger . warn ( " File config failed , using default " , e2 ) ;
connection = DriverManager . getConnection ( url , user , pass ) ; return g et D ef au lt V al ue ( key ) ;
} catch ( SQLException e ) { }

3
}
} // JUnit 5
@Test
public void t e s t I n v a l i d I n p u t () {
10 Best Practices assertThrows ( I l l e g a l A r g u m e n t E x c e p t i o n . class , () -> {
calculator . divide (10 , 0) ;
10.1 Exception Handling Guidelines }) ;
// DO : Be specific with exceptions }
try {
processFile ( filename ) ; // Testing exception message
} catch ( F i l e N o t F o u n d E x c e p t i o n e ) { @Test
logger . error ( " File not found : " + filename , e ) ; public void t e s t E x c e p t i o n M e s s a g e () {
} catch ( IOException e ) { Exception exception = assertThrows (
logger . error ( " I / O error processing file " , e ) ; I l l e g a l A r g u m e n t E x c e p t i o n . class ,
} () -> validator . validate ( null )
);
// DON ’T : Catch generic Exception unless necessary assertEquals ( " Input cannot be null " , exception . getMessage () ) ;
try { }
risky Operati on () ;
} catch ( Exception e ) { // too broad
// handle 12 Performance Considerations
}
• Exceptions are expensive - don’t use for control flow
// DO : Log and rethrow • Stack trace generation is costly
try { • Avoid exceptions in loops - validate inputs first
c r i t i c a l O p e r a t i o n () ;
} catch ( C r i t i c a l E x c e p t i o n e ) { • Use static factory methods for common exceptions
logger . error ( " Critical operation failed " , e ) ; • Consider lazy stack trace for high-frequency exceptions
throw e ; // don ’t swallow critical exceptions • Pool exceptions if creating many identical ones
}

// DON ’T : Empty catch blocks 13 Quick Reference


try {
risky Operati on () ; Checked vs Unchecked
} catch ( Exception e ) { • Checked: Must be caught or declared (IOException, SQLException)
// Silent failure - very bad ! • Unchecked: Runtime exceptions (NullPointerException, IllegalArgumentException)
}

// DO : Clean up in finally or use try - with - resources When to Use


try ( Resource resource = a c qu ir e Re so ur c e () ) { • Checked: Recoverable conditions caller should handle
useResource ( resource ) ;
} // automatic cleanup • Unchecked: Programming errors, invalid states

11 Exception Testing Exception Chain


• Use initCause() or constructor with cause parameter
11.1 JUnit Exception Testing • Preserves original stack trace and context
// JUnit 4
@Test ( expected = I l l e g a l A r g u m e n t E x c e p t i o n . class )
public void t e s t I n v a l i d I n p u t () {
Suppressed Exceptions
calculator . divide (10 , 0) ; • Added automatically in try-with-resources
} • Access via getSuppressed() method

You might also like