What You Need to Know About Exceptions in Java - dummies

What You Need to Know About Exceptions in Java

By Doug Lowe

An exception is an object that’s created when an error occurs in a Java program, and Java can’t automatically fix the error. The exception object contains information about the type of error that occurred.

The most important information — the cause of the error — is indicated by the name of the exception class used to create the exception. You usually don’t have to do anything with an exception object other than figure out which one you have.

A different exception class represents each type of exception that can occur. Here are some typical exceptions:

  • IllegalArgumentException: You passed an incorrect argument to a method.

  • InputMismatchException: The console input doesn’t match the data type expected by a method of the Scanner class.

  • ArithmeticException: You tried an illegal type of arithmetic operation, such as dividing an integer by 0 (zero).

  • IOException: A method that performs I/O (such as reading or writing a file) encountered an unrecoverable I/O error.

  • ClassNotFoundException: A necessary class couldn’t be found.

Here are the most important things you need to know about exceptions:

  • When an error occurs and an exception object is created, Java “throws an exception.” Java has a pretty good throwing arm, so the exception is always thrown right back to the statement that caused it to be created.

  • The statement that caused the exception can catch the exception if it wants it, but it doesn’t have to catch the exception if it doesn’t want it. Instead, it can duck and let someone else catch the exception. That “someone else” is the statement that called the method that’s currently executing.

  • If everyone ducks and the program never catches the exception, the program ends abruptly and displays a nasty-looking exception message on the console.

  • Two basic types of exceptions in Java are checked exceptions and unchecked exceptions:

    • A checked exception is an exception that the compiler requires you to provide for it one way or another. If you don’t, your program doesn’t compile.

    • An unchecked exception is an exception that you can provide for, but you don’t have to.