[Java] Exception Handling

There are three types of exceptions in Java: error, runtime exception, and checked exception. Only checked exception requires handling.

What are these exceptions?

  • Error:
Error refers to system errors, bugs in development tools, etc. In other words, errors are external to the application and out of the programmer's control. Examples include disk corruption, hardware malfunction, and system out of memory.

Recently my Eclipse has been refusing to compile my programs because it cannot find a certain file which comes with the software. It's a weird bug and every time I had to restart it to get it working. That is an example of an error.
  • Runtime Exception:
As the name suggests, runtime exception occurs at runtime, which means the compiler cannot catch it. Runtime exception typically indicates a bug in the code. Examples include NullPointerException, ArrayIndexOutOfBoundsException, etc. In other words, these are the exceptions that crash your program. 

Runtime exceptions do not require "handling". Rather, they require the programmer to look into the code and fix the bug. Here, "handling" refers to the specific exception handling technique which I will talk about next.
  • Checked Exception:
Again as the name suggests, checked exception refers to an exception that the compiler checks. A typical example is FileNotFoundException. When you want to read a file, if you type:

File file = new File("picard.txt");

This will not compile, because exceptions like this must be handled

How do we handle checked exceptions?

  • Surround with try/catch block:
The previous code can be fixed like this:

try {
  File file = new File("picard.txt");
} catch (FileNotFoundException fnfe) {
  System.out.println("Captain's not here");
}

This block of code tells Java to try open this file called "picard.txt". If a FileNotFoundException occurs, Java will execute the code in the catch block.

By using the try/catch block, the compiler will know that the exception is caught and compile the program. Opposite to catching the exception, you can also throw an exception.
  • Throw an exception:
A method which contains a checked exception can throw the exception using the throws keyword:

public void readFile() throws FileNotFoundException {
  File file = new File("picard.txt");
  // do something else
}

By throwing an exception, the method is saying that it is not responsible for catching the exception. And later when an object calls this method inside another method, the new method must either catch the exception or throw it again.

Comments

Post a Comment

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula