Skip to content

Exception Handling

trekitch edited this page Apr 11, 2017 · 6 revisions

What is an exception?

An exception is an unexpected or error condition. For example if you create a system for a user to enter their name then you output their name back to them. Now let's also say that you have a user that inputs a number instead of text. The most likely thing that will happen is that you will receive and error. This is because the program was only written to handle text. When you input a number instead it does not know what to do with this data and it crashes. Since the user enter a number instead of text was unexpected it is an exception.

Types of exceptions

The process of of resolving and managing exceptions is called exception handling. In Java their are two basic classes for errors: Error and Exception. Error is used for problems that are more serious. Exceptions, however, are less serious and usually can be easily fixed. Lets take the following code for example:

import java.util.Scanner;
public class Exception {
    public static void main(String args[]){
       Scanner keyboard = new Scanner(System.in);
       int numberOne;
       int numberTwo;
       int result;
       
       System.out.print("Enter your first number: ");
       numberOne = keyboard.nextInt();
       System.out.print("Enter second number: ");
       numberTwo = keyboard.nextInt();
       result = numberOne + numberTwo;
       System.out.println(result);
    }
    
}

This above code is normal enough. It asks the user to enter two numbers, adds the number together and output the result to the user. However, lets say that a user inputs a name instead of a number then they will be greeted with the following error message when they try to run the program.

Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Scanner.java:864)
	at java.util.Scanner.next(Scanner.java:1485)
	at java.util.Scanner.nextInt(Scanner.java:2117)
	at java.util.Scanner.nextInt(Scanner.java:2076)
	at javadoc.Exception.main(Exception.java:22)

This is what is know as a stack trace. This is how your compiler tries to help you find the source of the exception so that you can fix it. On the first line you can see that the compiler tells the user where the error has happened. In this case it was the main method. Next it tells you the type of exception has occurred. In this case it is a InputMismatchException. This happens when the data type that is received does not match the data type that the program is asking for. There are many other exception types such as an ArithmeticException, ArrayIndexOutOfBoundsException, and NullPointerException. These exceptions can be looked up at your own convenience.

Using try-catch to handle exceptions

Using a try-catch is a very common way to handle exceptions.

Clone this wiki locally