Java异常处理
Java异常处理
作用: 使程序可以处理非预期的错误,并且继续正常处理。
异常是从方法抛出的,方法调用者可以捕获并处理该异常
语法:
throw 抛出...
try{
... //正常语句
}
catch(){ //捕获
...
}
例子:
public class QuotientWithException {
public static int quotient(int number1, int number2) {
if (number2 == 0) //商不可以为0
throw new ArithmeticException("Divisor cannot be zero");//抛出一个异常
return number1 / number2;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
try {
int result = quotient(number1, number2);
System.out.println(number1 + " / " + number2 + " is "
+ result);//正常结果
}
catch (ArithmeticException ex) { //处理异常 ArithmeticException
System.out.println("Exception: an integer " +
"cannot be divided by zero ");//异常结果
}
System.out.println("Execution continues ...");
}
}
public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
//输入不是整数 InputMismatchException异常
// Display the result
System.out.println(
"The number entered is " + number);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" +
"Incorrect input: an integer is required)");
input.nextLine(); // 重新输入
}
} while (continueInput);
//continueInput = false;
}
}
java异常类继承关系图
More…
Java异常处理模型
1.声明一个异常(declaring an exception)
方法要抛出异常必须在方法头中显式声明,
方法调用者 会被告知有异常。
Public void method() throws IOException
//多个异常
public void myMethod()
throws Excepton1,Excepton2,...ExceptonN
2.抛出一个异常(throwing an exception)
throw new IllegalArgumentException("Wrong Argument")
🎈注意:声明是throws,抛出是throw
3.捕获一个异常(catching an exception)
try-catch多异常处理
try{
statements;
}
catch(Exception1 exVar1){
handler for exception1;
}
catch(Exception1 exVar2){
handler for exception2;
}
...
catch(Exception1 exVarN){
handler for exceptionN;
}
//如果在执行try块的过程中没有出现异常,则跳过catch子句。
🎈注意:若一个catch块可以捕获父类的异常对象,它就能捕获父类的所有子类的异常对象。
eg:
try{
...
}
catch(RuntimeException ex){
...
}
catch(Exception ex){
...}
posted on 2022-04-16 09:48 Michael_chemic 阅读(31) 评论(0) 编辑 收藏 举报