Groovy Vs Java - Exception Handling

 Some times java forces you to handle checked exception. Consider simple case: If you want to create object for FileInputStream, Java forces you to catch "FileNotFoundException".  For catching this exception almost every developers use  empty catch block. That's why normal Java application have lot of empty catch blocks like this.

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ExceptionHandling {
 public static void main(String[] args) {
  try {
   FileInputStream fin = new FileInputStream("D://sample.txt");
  } catch (FileNotFoundException e) {
   
  }
 }
}
 But Groovy does not force you handle the exception.  If any exception you don't handle is automatically passed on to a higher level. Groovier way for above example

def openFile() {
 //Here the exception is automatically redirected to caller method.
 new FileInputStream("D://sample.txt")
}

try{
 openFile()
}
catch(FileNotFoundException e) {
 println "File not found."
}

Comments