java小白的学习记录......
本文是 [java][34]异常1-异常机制总述后的第1篇,将介绍try-catch块。
1. 使用try-catch块捕获异常,分为三种情况
1)正常
2)异常匹配
3)异常不匹配
2. 示例
TestExceptionTry2.java
package Exception;
import java.util.Scanner;
public class TestExceptionTry2 {
public static void main(String[] args){
//自动生成 surrounded with -> try/catch block
try {
Scanner input=new Scanner(System.in);
System.out.println("Please input the 1st integer:");
int num1=input.nextInt();
System.out.println("Please input the 2nd integer:");
int num2=input.nextInt();
int result=num1/num2;
System.out.println("The result is:");
System.out.println(result);
}
catch(ArithmeticException ae){//具体异常
System.err.println("除数不能为0"+ae.getMessage());//System.err.println()输出红字,用于加入用户自定义处理信息
ae.printStackTrace();//printStackTrace的堆栈跟踪功能,显示出程序运行到当前类的执行流程
}
System.out.println("The program ends.");
}
}
测试:
1)正常
2)异常匹配
3)异常不匹配
可见:try-catch块后的语句没有执行
3. 异常对象常用方法
4. 常见异常类型
注:Exception e 包括所有异常
若把TestExceptionTry2.java的
catch(ArithmeticException ae){//具体异常
System.err.println("除数不能为0"+ae.getMessage());
ae.printStackTrace();
}
改为:
catch(Exception e){
e.printStackTrace();
}
再进行测试3),便会捕获到错误信息,如下图,try-catch块后的语句得到了执行