Home>

Use of java try and catch

Although the default exception handler provided by the java runtime system is useful for debugging,But usually i want to handle the exception yourself.This has two advantages.First, it allows you to fix errors.Second, it prevents the program from terminating automatically.Most users are annoyed by printing stack traces when the program terminates and whenever an error occurs (to say the least). Fortunately,This is easily avoided.

To prevent and handle a runtime error,Just put the code i want to monitor into a try block.Immediately following the try block, include a catch clause that specifies the type of error you wish to catch. It's easy to complete this task,The following program contains a try block that handles an arithmeticexception caused by division by zero and a catch clause.

class exc2 {
  public static void main (string args []) {
    int d, a;
    try {//monitor a block of code.
      d=0;
      a=42/d;
      system.out.println ("this will not be printed.");
    } catch (arithmeticexception e) {//catch divide-by-zero error
      system.out.println ("division by zero.");
    }
    system.out.println ("after catch statement.");
  }
}

The program output is as follows:

division by zero.
after catch statement.

Note that calls to println () in the try block are never executed.Once the exception is thrown,Program control is transferred from the try block to the catch block. Execution never "returns" from a catch block to a try block. Therefore, "this will not be printed."

Will not be displayed.Once the catch statement is executed, program control continues from the line below the entire try/catch mechanism.

A try and its catch statement form a unit.The scope of the catch clause is limited to the statements defined before the try statement.A catch statement cannot catch exceptions raised by another try statement (unless it is a nested try statement).

Statements protected by try must be enclosed in curly braces (that is,They must be in a block). You cannot use try alone.

The purpose of constructing the catch clause is to resolve the exception and continue to run as if the error did not occur.For example, in the following program,Each iteration of the for loop yields two random integers.These two integers are divided by each other,The result is used to divide 12345. The final result is stored in a. If a division operation results in a division by zero error,It will be captured,the value of a is set to zero,The program continues to run.

//handle an exception and move on.
import java.util.random;
class handleerror {
  public static void main (string args []) {
    int a=0, b=0, c=0;
    random r=new random ();
    for (int i=0;i<32000;i ++) {
      try {
        b=r.nextint ();
        c=r.nextint ();
        a=12345/(b/c);
      } catch (arithmeticexception e) {
        system.out.println ("division by zero.");
        a=0;//set a to zero and continue
      }
      system.out.println ("a:" + a);
    }
  }
}

Show an exception description

throwable overloads the tostring () method (defined by object), so it returns a string containing a description of the exception.You can display a description of the exception by passing it a parameter in println ().For example, the catch block of the previous program can be rewritten as

catch (arithmeticexception e) {
  system.out.println ("exception:" + e);
  a=0;//set a to zero and continue
}

When this version replaces the version in the original program,The program runs under the standard javajdk interpreter,Each division by zero error displays the following message:

 exception:java.lang.arithmeticexception:/by zero

Although there are no special values ​​in the context,The ability to display an exception description is valuable in other situations-especially when you experiment and debug exceptions.

The use of java multiple catch statement

In some cases,Multiple exceptions can be caused by a single code segment.Handle this situation,You can define two or more catch clauses, each of which catches one type of exception.When an exception is raised,Each catch clause is checked in turn,The first clause matching the exception type executes.When a catch statement is executed,The other clauses are bypassed,Execution continues from code after the try/catch block.The following example designs two different exception types:

//demonstrate multiple catch statements.
class multicatch {
  public static void main (string args []) {
    try {
      int a=args.length;
      system.out.println ("a =" + a);
      int b=42/a;
      int c []={1};
      c [42]=99;
    } catch (arithmeticexception e) {
      system.out.println ("divide by 0:" + e);
    } catch (arrayindexoutofboundsexception e) {
      system.out.println ("array index oob:" + e);
    }
    system.out.println ("after try/catch blocks.");
  }
}

The program runs under a starting condition without command line parameters causing a division by zero exception,Because a is 0. If you provide a command line argument,It will survive.Set a to a value greater than zero.But it will cause an arrayindexoutof boundsexception exception because the length of the integer array c is 1, and the program attempts to assign a value to c [42].

Here is the output of the program running in two different situations:

c:\>java multicatch
a=0
divide by 0:java.lang.arithmeticexception:/by zero after try/catch blocks.
c:\>java multicatch testarg
a=1
array index oob:java.lang.arrayindexoutofboundsexception after try/catch blocks.

When you use multiple catch statements, it is important to remember that exception subclasses must be used before any of their parent classes.This is because using the catch statement of the parent class will catch exceptions of that type and all its subclass types.Thus, if the child class is behind the parent class,Subclasses will never arrive.Moreover, unreachable code in java is an error.For example, consider the following program:

/* this program contains an error.
a subclass must come before its superclass in a series of catch statements. if not, unreachable code will be created and a compile-time error will result.
* /
class supersubcatch {
  public static void main (string args []) {
    try {
      int a=0;
      int b=42/a;
    } catch (exception e) {
      system.out.println ("generic exception catch.");
    }
    /* this catch is never reached because
    arithmeticexception is a subclass of exception. * /
    catch (arithmeticexception e) {//error-unreachable
      system.out.println ("this is never reached.");
    }
  }
}

If you try to compile the program,You will get an error message,The error message states that the second catch statement will not arrive,Because the exception has been caught.Because arithmeticexception is a subclass of exception, the first catch statement will handle all exception-oriented errors, including arithmeticexception. This means that the second catch statement will never execute.To modify the program,Reverse the order of two catch statements.

  • Previous ASPNET operations on txt files (read, write, save)
  • Next JavaScript multiple image upload case