异常
- 所有异常类都继承Throwable有两个子类,Error 和 Exception
- 使用try catch 和 try catch finally
- catch块必须子类在前父类在后。
public class TryCatchTest {
public static void main(String[] args) {
TryCatchTest te = new TryCatchTest();
int result = te.test();
System.out.println(result);
}
/**
* divider(除数):
* result(结果):
* 给定一个除数,每次循环除数减一,result = result + 100/divider。
* 如果捕获异常,打印输出“捕获异常了!!!”
* finally打印输出“这是finally!!!”
* 最后返回result = 999。
* @return
*/
public int test() {
int divider = 10;
int result1 = 0;
try {
while (divider > -1) {
result1 = result1 + 100/divider;
divider--;
}
} catch (Exception e) {
System.out.println("捕获异常了!!!");
}finally {
System.out.println("这是finally!!!");
}
return 999;
}
}
- 方法用throws关键字声明有异常,方法中throw该异常,调用者用try catch捕获,或者继续声明异常,给更上一层的调用者。
异常连:
public class ChainTest {
public static void main(String[] args) {
ChainTest test = new ChainTest();
try {
test.test2();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* test1抛出DrunkException异常。
* test2调用test1,捕获DrunkException异常,包装成RuntimeException。
* @throws DrunkException
*/
public void test1() throws DrunkException {
throw new DrunkException("喝大了!!");
}
public void test2(){
try {
test1();
} catch (DrunkException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}