Exceptions

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:

check.png IllegalArgumentException : You passed an incorrect argument to a method.

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

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

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

check.png ClassNotFoundException : A necessary class couldn’t be found.

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

check.png 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.

check.png 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.

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

check.png 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.

CrossRef.eps For more information, see Checked Exceptions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset