Exceptions are used to handle situations where something unexpected might happen, such as attempting to divide by zero, a file you're trying to access is not found, and more.
This tutorial focuses on:
- The various Java exceptions
- The try-catch block
- The try-catch-finally block
The various Java exceptions
Java has classes that can be used to handle exceptions in various situations.
- ArithmeticException - Used to handle arithmetic errors such as attempting to divide a number by zero. Located in the java.lang package.
- NoSuchMethodException - Used to handle a situation where a method is not found. Located in the java.lang package.
- IOException - Used to handle input/output errors. Located in the java.io package.
- FileNotFoundException - Used to handle a situation where a file cannot be found. Located in the java.io package.
NOTE: The base class of all the exception classes is the class Exception and it is located in the java.lang package.
The try-catch block
The way to deal with exceptions is to use a try-catch block. The try-catch block will execute one set of code if an exception does not occur, and a different set of code if an exception does occur. Specify within the try-catch block which exception it is you are watching for.
The try-catch-finally block
The try-catch-finally block is the same as the try-catch block with one addition. The try-catch-finally block contains a set of code that will execute whether an exception occured or not.