java异常 try-catch 和throw

异常处理1:try和catch捕获异常

package com.MissXu.blogTest;

import java.util.Scanner;

public class ExceptionTest {

	public static void main(String[] args) {
		
		System.out.println("---------begin---------");
		//背单词啦:divisor被除数、dividend除数、quotient商
		try {
			Scanner scan = new Scanner(System.in);
			System.out.print("Please input the divisor :");
			int divisor = Integer.parseInt(scan.nextLine()); //接收第一个整数作为被除数
			System.out.print("Please input the dividend :");
			int dividend = Integer.parseInt(scan.nextLine()); //接收第二个整数作为除数
			int quotient = divisor / dividend; //商
			System.out.println("result : " + quotient);
		} catch (NumberFormatException e) {
			System.out.println("数据格式异常:参数必须是数字!" + e);
		}catch (ArrayIndexOutOfBoundsException e){
			System.out.println("参数个数不对,必须是两个!" + e);
		}catch (ArithmeticException  e){
			System.out.println("除数不能为零!" + e);
		}catch(Exception e){ //为了防止漏写一些异常,可以加上Exception,但这个Exception必须写在最后
			System.out.println("发生了异常!" + e);
		}finally{
			System.out.println("I'll run whether there is a exception. "); //输出证明:不管异常与否程序都运行了
		}
		
		System.out.println("---------end---------");

	}

}


异常处理2:throw向上抛出异常

这里是一个标准的异常处理流程示例:

package com.MissXu.blogTest;

class Math{
	public int div(int i,int j) throws Exception{
		System.out.println("--------除法之前--------");
		int t=0;
		try{	
			t=i/j;
		}catch(Exception e){
			throw e;
		}finally{
			System.out.println("--------除法之后--------");
		}
			return t;
	}
}

public class ThrowTest {
	public static void main(String[] args) {
		Math m=new Math();
		try{
			int t=m.div(10,0);
			System.out.println(t);
		}catch(Exception e){
			System.out.println(e);
		}		
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值