throws语句
throws总是出现在一个函数头中,用来标明该成员函数可能抛出的各种异常。对大多数Exception子类来说,Java 编译器会强迫你声明在一个成员函数中抛出的异常的类型。如果异常的类型是Error或 RuntimeException, 或它们的子类,这个规则不起作用, 因为这在程序的正常部分中是不期待出现的。 如果你想明确地抛出一个RuntimeException,你必须用throws语句来声明它的类型。
throw语句
throw总是出现在函数体中,用来抛出一个异常。程序会在throw语句后立即终止,它后面的语句执行不到,然后在包含它的所有try块中(可能在上层调用函数中)从里向外寻找含有与其匹配的catch子句的try块。
以下为简单使用代码实例:package net.form1;
public class Throws {
public static void main(String[] args) {
Throws thr = new Throws();
thr.compute();
}
//定义可能会抛出异常的方法
//如果调用该方法,需要使用 try..catch处理异常
public void divider(int b,int c)throws Exception{
if(b == 0 || c == 0){
throw new Exception("除数不能为0");//抛出一个异常
}else{
System.out.println("相数相除的结果为:"+ b / c);
}
}
//可以处理异常的情况
public void compute(){
try{
this.divider(0, 3);
}catch (Exception e) {
//捕获divider方法出现的异常
System.out.println(e.getMessage());
}
}
//处理不了异常的情况
public void noset()throws Exception{
//...该方法如果处理不了异常,在次申明 throws ,将由调用noset()的方法处理异常
this.divider(0, 3);
}
}
自定义异常类package co.form1;
public class DrunkException extends Exception {
public DrunkException(){
}
public DrunkException(String message){
super(message);
}
}
使用自定义异常类package cn.form1;
public class ChainTest {
/**
* test1():抛出“喝大了”异常
* test2():调用test1(),捕获“喝大了”异常,并且包装成运行时异常,继续抛出
* main方法中,调用test2(),尝试捕获test2()方法抛出的异常
*/
public static void main(String[] args) {
ChainTest ct = new ChainTest();
try{
ct.test2();
}catch(Exception e){
e.printStackTrace();
}
}
public void test1() throws DrunkException{
throw new DrunkException("喝车别开酒!");
}
public void test2(){
try {
test1();
} catch (DrunkException e) {
// TODO Auto-generated catch block
RuntimeException newExc =
new RuntimeException(e);
//newExc.initCause(e);
throw newExc;
}
}
}
Exception:在程序中必须使用try...catch进行处理。
RuntimeException:可以不使用try...catch进行处理,但是如果有异常产生,则异常将由JVM进行处理。
对于RuntimeException的子类最好也使用异常处理机制。虽然RuntimeException的异常可以不使用try...catch进行处理,但是如果一旦发生异常,则肯定会导致程序中断执行,所以,为了保证程序再出错后依然可以执行,在开发代码时最好使用try...catch的异常处理机制进行处理。