您的位置:首页 > 职场人生

黑马程序员----Java的异常处理机制

2015-10-11 09:42 483 查看
/**
* @author Administrator
*
* @description 异常学习测试类
* @history
*/
public class ExceptionDemo {
/**
*@description
*@param args
*/
public static void main(String[] args) {
// Throable类是所有错误和异常的根基类
// Throable类下两个重要的子类Exception和Error
// 1、编写一个常见的异常例子
try {
int i = 1;
int j = 0;
int r = i / j;
} catch (ArithmeticException ae) {
ae.printStackTrace();
// Exception in thread "main" java.lang.ArithmeticException: / by zero
}
// 2、 catch多个种类的异常例子
String s1 = "1";
String s2 = "0"; // String s2 = "eclipse";
try{
int i1 = Integer.parseInt(s1); // 字符串解析成数字
int i2 = Integer.parseInt(s2);
int temp = i1/i2;
} catch(ArithmeticException ae){
ae.printStackTrace(); // 分母为0异常捕获
} catch(NumberFormatException nfe){
nfe.printStackTrace(); // 数字格式转换异常捕获
}
// 3、异常可以往上抛出去例子
int[] array = new int[5];
try{
int i3 = array[5]; // 数组越界异常
} catch(ArrayIndexOutOfBoundsException aiobe){

// 捕获异常后往外抛出
// 在某一层统一处理掉这些异常,比如可以采用拦截器
throw aiobe;
}
// 4、自定义异常类,继承自Exception类
try{
// 实例化内部类对象比较特殊点
ExceptionDemo out = new ExceptionDemo(); // 先实例化外部类对象
throw out.new MyException("hello-exception"); // 再实例化内部类对象
} catch(MyException me){
// hello-exception
System.out.println(me.getLocalizedMessage());
}
}
// 自定义异常类
class MyException extends Exception{
public MyException(String msg){
super(msg);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: