Ask Questions?

View Latest Questions

Advertisement


 
 

Exceptions
Posted on: July 26, 2006 at 12:00 AM
Java throws an exception

Java Notes

Exceptions

Java throws an exception

When your program causes an error, Java throws an exception. Java then throws this exception to a part of the program that will catch it. You shouldn't try to catch most exceptions, but you should catch all exceptions that are caused by events which you have no control over - exceptions caused by bad user input or I/O problems.

Processing an exception

When an exception is thrown, execution of that statement stops immediately and Java looks for someone to catch the exception.

  1. It looks to see if the code that caused the exception is inside a try statement that can handle the exception. If the try statement has a catch clause that can handle this type of exception, then it goes to that code. After catch clause is executed, execution resumes after the end of the entire try statement. It's not possible to return to the point at which the exception was thrown.
  2. If there is no try statement around the code that threw the exception, Java goes up the call stack and looks at the statement that called this method, and checks for a try statement surrounding the call. If it finds an enclosing try statement that has a catch clause for this kind of exception, the catch clause is executed and then execution continues after that try statement. Java continues moving up the call stack until it finds an enclosing try statement.
  3. If no enclosing try statement and catch clause is found, the exception is caught by the initial Java system method that called main initially. It prints an error message and terminates the program.

try...catch statement catches exceptions

Put a try...catch statement around any section of code that might generate a user generated exception (eg, converting text field input to numbers). The simplest form is:

   try {
      . . . // Normal statements that might cause a problem
   } catch (exception-name parameter-name) {
      . . . // Statements to execute if exception-name occurred.
   }

Example

If the user types an illegal value into a JTextField that expects an integer (eg, "123X45"), attempting to convert with Integer.parseInt will throw a NumberFormatException.

txt = aTextField.getText();
try {
    . . .  // other code
    i = Integer.parseInt(txt);
    . . .  // process the input
catch (NumberFormatException nfe) {
    aTextField.setText("Enter an integer");
}

Also see Example - Calc Main.

Advertisement


DMCA.com