首页 > 编程语言 > 详细

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

时间:2015-10-11 10:06:14      阅读:289      评论:0      收藏:0      [点我收藏+]

/**
* @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);
}
}
}

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

原文:http://www.cnblogs.com/castworld/p/4868805.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!