Catching Exceptions

Handling Exceptions

Catching Exceptions

🙋 Need help? Ask an expert now!

Exceptions are the root cause of runtime errors. An exception is something that happens while the program is executing. Whatever this exception may be, it interrupts or breaks the normal flow of the program's executable directions. Let's dive deeper into what exception errors are and how we can detect and resolve them!
package exlcode;

public class CatchingExceptionExample {

  public static void main(String[] args) {
    try {
      // NumberFormatException will be thrown because a String
      //  with characters cannot be converted into an integer value
      String exampleVariableOne = "Hello World!";
      int exampleVariableTwo = Integer.parseInt(exampleVariableOne);
    } catch (NumberFormatException e) { // the character 'e' is commonly used, but you are free to name it whatever
      // If a NumberFormatException is thrown, the program
      // will print "Number Format Exception"
      System.out.println("Number Format Exception");

In the scenario above, an error is supposed to occur because we try to convert characters into integers. Instead of the error, the program caught the exception "NumberFormatException" itself, and printed out a different result specified by us beforehand.

How do we catch an exception? Set the code that might throw the error inside a try{} block. Then, set the code that catches and handles the exception inside a catch{} block. Then, when the program runs, if there is a statement inside the try{} block that throws a "NumberFormatException", it causes the catch{} block to execute, causing the leftover statements in the try{} block to remain unexecuted. Remember that the catch{} block is executed only if the exception thrown in the try{} block matches the exception inside the parentheses of the catch{} block.

Edit Me on GitHub!

Application Question

Which of these Java reserved words must be used to handle the exception thrown by the try block?