Java异常
1. 异常
2. Error和Exception
(1)Error
(2)Exception
3. 异常处理机制:捕获和抛出异常
异常处理五个关键字:try、catch、finally、throw、throws
代码示例
package com.baidu.www;
public class test {
public static void main(String[] args) {
int a = 1;
int b = 0;
// try...catch...finally...
/**
* Ctrl + Alt + T键 快捷键生成语句
*/
try{ // try 监控区域
System.out.println(a/b);
}catch (ArithmeticException e){ // catch 捕获异常
System.out.println("出现异常!");
}finally { // 处理善后工作
/**
* 假设I/O、资源,需要关闭!
*/
System.out.println("嘻嘻!");
}
try {
new test().a();
}catch (StackOverflowError s){ // Throwable / Error / Exception /
System.out.println("栈溢出异常!");
}catch (Error e){
System.out.println("错误!");
}catch (Throwable t){
System.out.println("异常!");
}
// throw
// new test().test(1, 0);
// throws
try {
new test().test(1, 0);
} catch (ArithmeticException e) {
throw new RuntimeException(e);
}
}
public void a() {b();}
public void b() {a();}
// 假设方法中无法处理异常
// 方法上抛出异常
public void test(int a, int b) throws ArithmeticException{
// 主动抛出异常
// 一般在方法中使用
if(b == 0){
throw new ArithmeticException(); // 主动抛出一个异常
}
System.out.println(a/b);
}
}
4. 自定义异常及经验
代码示例
(1)MyException类
package com.baidu.www;
// 自定义异常类
public class MyException extends Exception{
// 传递数字 > 10;
private int detail;
public MyException(int a){
this.detail = a;
}
// toString:异常的打印信息
@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
'}';
}
}
(2)test类
package com.baidu.www;
public class test {
// 可能会存在异常的方法
static void test(int a) throws MyException{
System.out.println("传递的参数为:" + a);
if(a > 10){
throw new MyException(a); // 抛出
}
System.out.println("OK!");
}
public static void main(String[] args) {
try{
test(1);
test(78);
}catch (MyException e){
e.printStackTrace();
}
}
}
Alt + Enter快捷键