Tricky Tricks ›› Programming Tricks ›› Java Tricks ›› Don't Catch Every Exception

Don't Catch Every Exception

Java Programming Tricks

Don't catch every exception:

 Many Java methods throw checked exceptions. You notice them when the 
 compiler complains: 
 
 public void writeStack(DataOutput out) 
 
 { for (int i = 0; i < 100; i++) 
 
 { String s = (String) stk.pop(); // error: throws EmptyStackException 
 
   out.writeChars(n); // error: throws IOException 
 
 }
 
 }
 
 The first instinct is to surround each line with a try/catch clause. 
 
 public void writeStack(DataOutput out) 
 
 { for (int i = 0; i < 100; i++) 
 
 { String s 
 
 try 
 
 { s = (String)s.pop(); 
 
 }
 
 catch (EmptyStackException ese) 
 
 {// stack was empty 
 
 } 
 
 try 
 
 { out.writeChars(s); 
 
 }
 
 catch (IOExcep=ioe ioe) 
 
 { // problem writing file 
 
 }
 
 }
 
 }
 

Sitemap : Partners