Think in Java 笔记_Chapter12_1_Exception基础_异常处理2

异常处理方式2

  1. throw向上抛出

    package cn.seven.shengsiyuan.exception;
    
    
    /*
     * 2015年04月05日13:05:35
     * Location:501
     * 
     * 异常处理方法2:抛出异常,由调用该方法的方法  进行处理该异常
     */
    public class ExceptionThrowDemo {
    
    	public static void main(String[] args) throws Exception {
    		// TODO Auto-generated method stub
    
    		ExceptionThrowDemo demo = new ExceptionThrowDemo();
    		//demo.method();//若直接这样写 出现 Unhandled exception type Exception
    		demo.method();//因此需对该异常进行处理:两种方式,1.自己处理 2.向上抛出:main方法中抛出到最后就是虚拟机进行处理了
    		
    	
    	}
    
    	public void method () throws Exception{//告诉调用该方法这个其他方法,我这个方法会抛出异常
    		
    		
    		System.out.println("hello");
    		throw new Exception();//抛出一个异常对象,因为所有的一场都是异常
    	}
    }
    

     

  2. 有些异常 编译时候 可以通过,有些异常不可以通过,为何?

      1. int a = 3;
        int b = 0;
        int c= a / b;//这里即使可能抛出异常,但是编译通过,运行时抛出异常`    
        System.out.println("---hello---");
        

      2. /* 抛出的异常,编译不通过,因为异常的类型: --CheckedException(非运行时异常), 在编译时候就需要进行处理_处理方式两种: 1,try{}catch{} 2, 在调用该会产生异常的方法 所在的方法声明 throws Exception --对于UncheckedException(运行时异常), 如c=a/b;我们可以对其进行处理,也可以不处理,推荐不处理 */ public static void main(String[] args) { ExceptionThrowDemo demo = new ExceptionThrowDemo(); demo.method();//若直接这样写 出现 Unhandled exception type Exception } public void method () throws Exception{//告诉调用该方法这个其他方法,我这个方法会抛出异常 System.out.println("method"); throw new Exception();//抛出一个异常对象,因为所有的一场都是异常 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值