[java][35]异常2-try catch

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块后的语句得到了执行


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值