1、使用throws关键字抛出异常:
throws将代码中可能产生的异常交给别人来处理
语法:
public void method() throws 异常类型1,异常类型2,...异常类型n{
}
创建方法时,可以使用throws将可能发生的异常抛出,抛出以后该方法就不需要用try-catch来处理,当调用一个含有throws声明异常抛出的方法时,要求必须处理该异常,而处理方式有两种:1)使用try-catch捕获并解决异常,2)在当前方法上继续使用throws声明该异常的抛出。
//被调用时
try{
method();
}catch(异常类型 e){
e.printStackTrance();
}
2、例子:调用含有throws声明异常排出的方法时,使用try-catch处理异常
public class Demo{
public static void snow() throws InterruptedException{
for(int i =0;i<10;i++){
System.out.println(i);
Thread.sleep(1000);//睡眠1s
}
}
public static void main(String[] args){
try{
show();
}catch(InterruptedException e){
e.printStackTrance();
}
}
}
或直接继续使用throws抛出:
public class Demo{
public static void snow() throws InterruptedException{
for(int i =0;i<10;i++){
System.out.println(i);
Thread.sleep(1000);//睡眠1s
}
}
public static void main(String[] args) throws InterruptedException{
show();
}
}
注意:需要自己处理的异常千万别抛出,自己处理不了的问题一定要抛出去,若自己能处理的异常一直使用throws抛出的话,最终会交给Java虚拟机处理该异常,一旦出错,会直接将错误抛到页面或客户端,会造成用户体验性不好或者代码泄露。