Home

Published

- 2 min read

Java: Multiple Functions and one ErrorHandler

img of Java: Multiple Functions and one ErrorHandler

Let’s say you have function fooA() and function fooB() both functions are very similar and throw similar errors.

 public static void fooA(){
         try{
             throw new FileNotFoundException();
         }
         catch (Exception e){
             exceptionHandler(e);
         }
     }

     public static void fooB(){
         try{
             throw new FileNotFoundException();
         }
         catch (Exception e){
             exceptionHandler(e);
         }
     }

If you have the possibility to avoid duplicating code you could write a single Error handler and pass the Error to the Error handling function. However, you still want to be able to distinguish between different types of Exception and for logging purposes, you should mention which function actually caused Exception. The easiest way to figure the Method name is to use e.getStackTrace()[0].getMethodName(); Alternatively, you can pass the method name to the Errorhandlerfunction. To do that you can figure out the method name via:

 String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();

To determine the various Exceptions there are two possibilities:

Method 1: Use instanceof

The downside to this method is that it is not as readable and identifiable as ErrorHandling function. (However, this depends on personal preferences)

     public static void exceptionHandler(Exception e){
         if (e instanceof FileNotFoundException){
             System.out.println(e + " " + e.getStackTrace()[0].getMethodName());
         } else if (e instanceof Exception) {
             System.out.println(e.getStackTrace()[0].getMethodName());
         }
     }

Method 2: re-throw the Error

Well, you are still throwing around with errors, but it is clearly identifiable as Error handler.

  public static void exceptionHandler(Exception e){
         try {
             throw e;
         }
         catch (FileNotFoundException e){
             System.out.println(e + " " + e.getStackTrace()[0].getMethodName());
         }
         catch(Exception e) {
             System.out.println(e.getStackTrace()[0].getMethodName());
         }
     }