Checker ExceptionHandlers   as of Julia version 2.5.0 (built on 4 Jul 2018)

belongs to group Basic

Identify possibly incorrect exception handlers


This checker controls if exception handlers might be incorrect. For instance, an exception handler with an empty body might be an unfinished snippet of code; an exception handler for a very generic exception type might end up catching too many exceptions, also some that were not meant to be caught there.

Action: Add a body to the exception handler, or narrow to the exception types.

Examples


Consider the following program:

import java.io.FileWriter;

public class Main {
  public static void main(String args[]) {
    FileWriter fw = null;
    try {
      fw = new FileWriter(args[0]);
      fw.close();
    }
    catch (IndexOutOfBoundsException e) {}
    catch (Exception e) {
      System.out.println("unusual");
    }
  }
}

This checker issues the following warnings:

Main.java:10: [ExceptionHandlers: EmptyExceptionHandlerWarning] Empty exception handler for java.lang.IndexOutOfBoundsException
Main.java:11: [ExceptionHandlers: GenericExceptionHandlerWarning] Exception handler for the very generic type java.lang.Exception

In this example, the programmer could for instance issue a warning message to the user, asking to provide an argument when invoking the program. Moreover, he should narrow the kind of exceptions caught by the second exception handler to java.io.IOException:

import java.io.FileWriter;

public class Main {
  public static void main(String args[]) {
    FileWriter fw = null;
    try {
      fw = new FileWriter(args[0]);
      fw.close();
    }
    catch (IndexOutOfBoundsException e) {
      System.out.println("usage: Main filename");
    }
    catch (IOException e) {
      System.out.println("I/O error");
    }
  }
}

Sometimes, an empty handler is needed since the compiler does not know that an exception will never be thrown there. If Julia recognizes that situation, it will not issue any warning for the empty exception handler. For instance, in the following program:

public class CloneOK implements Cloneable {
  private int f;

  public CloneOK(int f) {
    this.f = f;
  }

  @Override
  protected Object clone() {
    CloneOK result = null;

    try {
      System.out.println("Starting cloning");
      result = (CloneOK) super.clone();
      result.f = f;
      System.out.println("Finished cloning");
    }
    catch (CloneNotSupportedException e) {
    }

    return result;
  }

  public static void main(String[] args) {
    new CloneOK(13).clone();
  }
}

This checker will not issue any warning, since the call to super.clone() is applied to a cloneable object this and will consequently never throw a CloneNotSupportedException. The programmer must nevertheless write that empty handler, since otherwise the compiler will not compile the program.