Basic exception handling

WHEN WE EXECUTE a bit of code there is almost always the possibility for something to break. Sometimes it can be the purpose of the code to break because if it didn’t do so the consequences might be more severe. When these cases arise we call them exceptions or exceptional events.

To explain this in it’s most simple state we can look at a very small program which consist of a parent-class (main) and a child-class (subMeth) in which the child-class tries to divide an integer with zero.

public class TopDog {
  public static void main(String[] args) {
    SmallDog(5,0);
  }

  public static void SmallDog(int first, int second) {
    int average  = first/second;
  }
}

WHEN DIVISION BY ZERO is executed the engine will scream from the top of it’s lungs at the child telling him/her that division by zero is fobidden. Of course the child will run to it’s closest parent and start weeping. And due to the fact that parents usually are quite bad at math the problems can not be solved even here and this makes the entire world collapse. I.e the application close.

So, how do we stop the sky from falling? We build a way for the application to solve the problem when it arise so that the parent don’t need to receive the problem at all. To do this we use the keywords try and catch.

public class TopDog {
  public static void main(String[] args) {
    try {
      SmallDog(5,0);
    }
    catch (Exception e) {
      System.out.println(”Exception : “+ e.getMessage());
    }
  }

  public static void SmallDog(int first, int second) {
    int average  = first/second;
  }
}

This would make the same exception to be thrown from division by zero but we will catch the error and let the application continue while explaining for the user what happened. Output to use would give the same error as before but the application do not crash.

SOMETIMES WE WANT to execute a bit of code after a try regardless of an exception is thrown or not. It could be a file we tried to read from that we of course would like to close to not let memory and sockets linger. In Java this is possible by using the keyword finally. The finally keyword always come just after a try or catch. No extra code can be written in between.

public class TopDog {
  public static void main(String[] args) {
    try {
      SmallDog(5,0);
    }
    catch (Exception e) {
      System.out.println(”Exception : “+ e.getMessage());
    }
    finally {
      System.out.println("The end of the line.");
    }
  }

  public static void SmallDog(int first, int second) {
    int average  = first/second;
  }
}

In this example the string “The end of the line” would be printed regardless if an exception was thrown or not.

Leave a Reply

Your email address will not be published. Required fields are marked *