Initial knowledge of Java exception handling
- The following procedure, although can run, but when the data input is wrong, the program does not end normally, that is, the program itself is not handled abnormally.
Example 001 Write a program in Java. Enter two integers to output their quotient.
Import Java.util.Scanner;
public class Myadd {
public static void Main (string[] args) {
Scanner in = new Scanner (system.in);
int a = In.nextint ();
int b = In.nextint ();
int div = A/b;
System.out.println ("a/b=" + div);
}
}
- The following procedures, although the exception can be handled, but the abnormal effect of the relevant code separation, there is no good grasp of the exception processing logic.
Example 002 Write a program in Java. Enter two integers to output their quotient.
Import java.util.InputMismatchException;
Import Java.util.Scanner;
public class Mydiv {
int A, B, di;
public MyDiv() { super(); try { Scanner in = new Scanner(System.in); a = in.nextInt(); b = in.nextInt(); } catch (InputMismatchException e) { System.out.println("输入数据有误!"); }}int caculate() { try { di = a / b; } catch (ArithmeticException e) { System.out.println("除数为零!"); } return di;}public static void main(String[] args) { MyDiv div = new MyDiv(); System.out.println("a/b=" + div.caculate());}
}
For example, when you enter AA BB, the program results are:
Wrong input data!
Divisor is zero!
A/b=0
3. It is a good practice to put the relevant code of the exception effect together, put in try{}, with the relevant catch (...) for each exception. {...} Processing.
Example 003 Write a program in Java. Enter two integers to output their quotient.
Import java.util.InputMismatchException;
Import Java.util.Scanner;
public class Mydiv {
public static void Main (string[] args) {
try {
Scanner in = new Scanner (system.in);
int a = In.nextint ();
int b = In.nextint ();
int div = A/b;
System.out.println ("a/b=" +div);
} catch (Inputmismatchexception e) {
SYSTEM.OUT.PRINTLN ("Wrong input data! ");
}
catch (ArithmeticException e) {
System.out.println ("Divisor is zero!") ");
}
}
}
Programs like this, can be in the event of an exception, the program can be logical and normal operation.
Problems about Java exception Handling in program design