异常之try-catch-finally语句

异常分类
Java所有的异常(Exception)都是派生自Throwable,异常是可以被捕获的。而错误(Error)是不能被捕获的。这里详细介绍Java的异常捕获机制(try-catch语句)

1.最简单的try-catch语句

int x=10;
try {
	System.out.println(x);   //代码块
	int y=x/0;
	System.out.println(y);
}
catch(Exception e) {
	e.printStackTrace();     //catch块
	System.out.println(x);
}

捕获异常如下
在这里插入图片描述
从这个例子中我们可以看出,try中的代码报错,则下面的代码不会再执行,转而执行catch代码块
2.自定义异常
自定义异常一般情况下要继承RuntimeException类

public class define_exception extends RuntimeException {

    /**
	 * 重写fillInStackTrace()方法
	 */
	private static final long serialVersionUID = 1L;
	public synchronized Throwable fillInStackTrace() {
		System.out.println("Exception occurring");
        return this;
    }
	public static void main(String[] args) throws define_exception{	
        throw new define_exception();
  }    
    
}

3.多重catch语句
一个代码块可能产生多个异常,这时,我们可以采用多重catch语句捕获多个异常

public class Multi_Catch {
	public static void main(String[] args){
          try {
        	  System.out.println(10/0);	  
          }
          catch(define_exception e) {
        	  e.printStackTrace();
          }
          catch(RuntimeException e) {
        	  e.printStackTrace();
          }
          catch(Exception e) {
        	  e.printStackTrace();
          }
    }
}

父类异常一定要写在子类异常的后面,因为父类异常会捕获所有类型的子类异常,否则会报错
在这里插入图片描述
4.try-catch-finally
finally代码块无论如何一定执行

public class Try_Catch_Finally {
	public static void main(String[] args){	
		try {
			System.out.println("Normal operation1");
			int x=10/0;
			System.out.println("Normal operation2");
		}
		catch(Exception e){
			System.out.println("Normal operation3");
		}
		finally {
			System.out.println("Normal operation4");
		}
    }
}

运行结果如下:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值