Thursday, October 6, 2016

How to Handle Exceptions in Java

There are many different concepts to learn when learning a programming language. Many of these concepts are like grammar in spoken languages – they help keep it structured and functioning properly. Handling exceptions in Java is an important skill in becoming a good Java programmer.

Exceptions are thrown when the program has encountered an error. Once the exception is thrown, it is up to the programmer to decide what happens next. The most common and the worst handling of an exception is silently ignoring it. Printing stack trace to the console should at least be done so that pinpointing an error is easier.

EditChecked vs Unchecked Exceptions

Checked exceptions are classes derived from Exception class and are thrown when the program can recover from the exception and they must either be caught using one of the try blocks or rethrown. Unchecked exceptions are classes derived from RuntimeException and are thrown when the program cannot recover from the exception and they don't have to be caught or rethrown. Generally, unchecked exceptions are a result of a programming error and can be avoided (e.g. checking if a variable is null to prevent NullPointerException).

Since unchecked exceptions produce cleaner code, programmers favor it over checked exceptions and nowadays it basically comes down to a personal choice. However, exceptions in the Java API abide the difference.


Exception examples:
Checked Unchecked
IOException NullPointerException
ClassNotFoundException IllegalArgumentException
InterruptedException IllegalStateException

EditSteps

EditUsing Try-Catch-Finally

  1. Handle exceptions in java method1 step1.png
    Create a class and the main method. Create a class and name it however you want and inside the class create the main method.
    public class HandleExceptionExample {
        public static void main(String[] args) {
     
        }
    }
    
  2. Handle exceptions in java method1 step2.png
    Declare three primitive integer variables and perform division. Declare three int (primitive integer) variables and name them dividend, divisor and quotient. Assign an arbitrary number to dividend variable, assign zero to divisor variable and assign quotient of dividend and divisor to quotient variable. Print quotient variable to the console.
    public class HandleExceptionExample {
        public static void main(String[] args) {
            int dividend = 50;
            int divisor = 0;
            int quotient = dividend / divisor;
            System.out.println(quotient);
        }
    }
    
  3. Handle exceptions in java method1 step3.png
    Compile and run the program. Program prints exception stack trace to the console and terminates the execution at the line where the quotient variable is assigned a value. Quotient variable will never be printed to the console because uncaught exceptions, on the line they were thrown, break out of the method.
  4. Handle exceptions in java method1 step4.png
    Catch and handle exception. Assign a number zero to the quotient variable and create try-catch block with ArithmeticException in the catch statement. Inside the try block, divide dividend and divisor variables and assign their quotient to the quotient variable. Inside the catch block, print the exception stack trace to the console. After the try-catch block, print the quotient variable to the console.
    public class HandleExceptionExample {
        public static void main(String[] args) {
            int dividend = 50;
            int divisor = 0;
            int quotient = 0;
            try {
                quotient = dividend / divisor;
            } catch (ArithmeticException e) {
                e.printStackTrace();
            }
            System.out.println(quotient);
        }
    }
    
  5. Handle exceptions in java method1 step5.png
    Compile and run the program. Program prints exception stack trace to the console, but does not terminate the execution at the line where the quotient variable is assigned a value. Quotient variable is also printed to the console, but before the exception.
  6. Handle exceptions in java method1 step6.png
    Add finally block. finally blocks are always executed after the try and/or catch blocks and they are mostly used to release the resources. Instead of after the try-catch-finally block, print the quotient variable to the console inside the finally block.
    public class HandleExceptionExample {
        public static void main(String[] args) {
            int dividend = 50;
            int divisor = 0;
            int quotient = 0;
            try {
                quotient = dividend / divisor;
            } catch (ArithmeticException e) {
                e.printStackTrace();
            } finally {
                System.out.println(quotient);
            }
        }
    }
    
  7. Handle exceptions in java method1 step7.png
    Compile and run the program. Program prints exception stack trace, and quotient variable right after, to the console.

EditUsing Try-With-Resources

  1. Handle exceptions in java method1 step1.png
    Create a class and the main method. Create a class and name it however you want and inside the class create the main method.
    public class HandleExceptionExample {
        public static void main(String[] args) {
     
        }
    }
    
  2. Handle exceptions in java method2 step2.png
    Create try-catch block. Create try-catch block and add parenthesis to the try statement.
    public class HandleExceptionExample {
        public static void main(String[] args) {
            try () {
     
            } catch () {
     
            }
        }
    }
    
  3. Handle exceptions in java method2 step3 fixed.png
    Add resource to the try and exception to the catch statement. Instantiate FileReader and File as its parameter in the try statement. In the catch statement, add IOException and inside the block, print stack trace to the console.
    public class HandleExceptionExample {
        public static void main(String[] args) {
            try (FileReader reader = new FileReader(new File("filename"))) {
                // code omitted
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
  4. Handle exceptions in java method2 step4.png
    Finished. Using try-with-resources automatically releases the resources back to the operating system. Think of it as an automatic finally block. If exception is thrown while reading the file, reader.close() will be automatically called.
    • The equivalent using try-catch-finally:
      FileReader reader = null;
      try {
          reader = new FileReader(new File("filename"));
          // code omitted
      } catch (IOException e) {
          e.printStackTrace();
      } finally {
          if (reader != null) {
              try {
                  reader.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      

EditVideo

EditTips

  • If you're unsure of what exception to catch, you can always catch the superclass for all exceptions, the Exception class.
  • Catching and handling more than one exception is possible. There are multiple ways to do so:
    • To catch and handle multiple exceptions separately, add another catch statement and block at the end of the try-catch block.
      try {
          Socket socket = new Socket("localhost", 5940);
      } catch (UnknownHostException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }
      

      UnknownHostException will only be caught if it is located before the IOException since the former is derived from the latter. Otherwise it will be caught with IOException. If there is no need to go into detail with exceptions, only the superclass needs to be caught.

      try {
          Socket socket = new Socket("localhost", 5940);
      } catch (IOException e) {
          e.printStackTrace();
      }
      
    • To catch and handle multiple exceptions together, add multiple exceptions in the same catch statement separated by the | character. However, those exceptions must have different superclasses. For example, UnknownHostException and IOException cannot be caught like this because the latter is a superclass of the former.
      try {
          Socket socket = new Socket("localhost", 5940);
      } catch (IllegalArgumentException | IOException e) {
          e.printStackTrace();
      }
      

EditWarning

  • Silently ignoring is a bad practice and the worst method of exception handling. Example of silently ignoring an exception:
    try {
        // code omitted
    } catch (Exception e) {
    }
    

EditRelated wikiHows




No comments:

Post a Comment