Java——抛出异常

第一种:捕获异常:

第二种:把“锅”甩给Java虚拟机:

throw 关键字

throw关键字的作用是:主动抛出异常

首先我们来看系统自动抛出异常:

 
  1. public static void main(String[] args) {
  2. int a = 10;
  3. int b = 0;
  4. System.out.println(a/b);
  5. }

运行这段代码系统会自动抛出,java.lang.ArithmeticException异常。

这段程序使用throw关键字也可以实现:

 
  1. public static void main(String[] args) {
  2. int a = 10;
  3. int b = 0;
  4. if(b == 0){
  5. throw new ArithmeticException("/ by zero");
  6. }
  7. System.out.println(a/b);
  8. }

可以发现两段程序的运行结果都类似:

throw是语句抛出一个异常,一般是在代码块的内部,当程序出现某种逻辑错误时由程序员主动抛出某种特定类型的异常

注意:使用throw关键字主动抛出检测性异常的时候,在方法名上必须使用throws表明调用这个方法可能存在要抛出的异常。

举个例子:

ArithmeticException属于运行时异常,是在运行时检测的,所以上述代码编译是能通过的,而FileNotFoundException是属于检测性异常,是在编译之前就需要处理的,所以第二段程序要加上throws才能通过编译。

package step3;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Task {
	/********* Begin *********/
	//请在合适的部位添加代码
	public static void main(String[] args)throws FileNotFoundException
    {	
		test();
	}
	public static void test() throws FileNotFoundException{
		File file = new File("abc");
		if(!file.exists()){		//判断文件是否存在
			//文件不存在,则 抛出 文件不存在异常
			throw new FileNotFoundException("该文件不存在");
		}else{
			FileInputStream fs = new FileInputStream(file);
		}
	}
	/********* End *********/
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值