EC

  • Edwin Chan
  • CV
  • CPSC 233
  • CPSC 331
  • CPSC 355
  • CPSC 581
  • Origami
  • Random

Tutorial 12 (March 29): Exception handling

This week we will cover exception handling, which is an important aspect of creating usable code. We will cover Displays 9.4, 9.5, 9.8, and 9.10, as well as the finally clause

When you are designing for any problem, there are a lot of use cases that may cause the program to run into an error; we call this error an exception. When such an exception occurs, the program may be put into an undesired state, often resulting in a crash. To prevent these problems, we do what's called exception handling. To handle an exception means to expect that an error can occur, and to tell the program what to do when such an error occurs.

Such common exceptions include:

  • divide by zero exception
  • array out of bounds index exception
  • null pointer exception
  • format mismatch exception

While writing programs, you will have to handle many exceptions. On the flip-side, if you were to write libraries (or packages in Java) for other programmers to use, you might want to tell them if a certain error occurs. In such a case, you can implement your own types of exceptions, which can then be handled by the people using your code.

Key terms:

  • Exception: some type of error
  • Throws: usually used as part of the method stub to declare what type of exceptions may occur from using the method, eg. public void divideNumbers() throws DivisionbyZeroException
  • Try: the code to try running, hoping for no exceptions
  • Catch: try to catch an error you may be expecting, and tell the program what to do in such a case
  • Finally: code to run at the end of the try-catch, regardless of whether an error occurred or not
  • Exception handling: to catch errors; if an error is not handled (ie. not caught and dealt with), your program will likely crash or result in undesired behavior

When implementing your own exceptions, it is important to call the super constructor with both these signatures:

  1. super("Your predefined default error message.")
    • specifies default error message
  2. super(message)     
    • message is a String which can be passed when throwing the rror, eg. throw new DividionByZeroException("Dividing by zero, are you crazy?!");
  • Edwin Chan
  • CV
  • CPSC 233
  • CPSC 331
  • CPSC 355
  • CPSC 581
  • Origami
  • Random