黑马程序员技术交流社区
标题:
Java 异常/多异常的处理
[打印本页]
作者:
_Water
时间:
2014-4-2 21:37
标题:
Java 异常/多异常的处理
/*一.异常的处理:
java 提供了特有的语句进行处理
try
{
需要被检测的代码
}
catch(异常类 变量){
处理异常的语句
}
finally{
一定会执行的语句
}
二.对捕获的异常对象进行常见方法操作
String getMessage();获取异常信息
类Excetion 是继承于Throwable类的
class Throwable
{
private String message;
Throwable(String message)
{
this.message=message;
}
public String getMessage()
{
return message;
}
}
class Exception extends Throwable
{
Exception (String message)
{
super(message);
}
}
在函数上声明异常的好处:
1.提高安全性
2.让调用者进行处理,不处理编译失败
三.对多异常的处理:(函数中只要有异常发生就不会进行了,要退出了)
1.声明异常时,建议声明更为具体的异常,这样处理的更具体ArithmeticException
2.对方声明几个异常,就对应有几个catch块(不要定义多余的catch块)
如果多个catch块中的异常出现继承关系,父类异常catch块放在最下面
独立在进行catch处理时,catch中一定要定义具体的处理方式。
不要简单定义一句e。printStackTrace();
也不要简单的就书写一条输出语句。
*/
class Demo
{
int div(int a ,int b)throws ArithmeticException,ArrayIndexOutOfBoundsException//在功能上通过throws的关键字声明了该功能可能会出现问题
{
int[] arr =new int[a];
System.out.println(arr[2]);
return a/b;
}
}
class ExceptionDemo
{
public static void main(String[] args)
{
Demo d =new Demo();
try
{
int x =d.div(2,2);
System.out.println(x);
}
catch (ArithmeticException e)//Exception e =new ArithmetricException();多态
{
System.out.println("div by zero ");
System.out.println(e.getMessage()); // / by zero;
System.out.println(e.toString());//异常名称:异常信息
e.printStackTrace();//异常名称:异常信息,异常出现的位置
//其实JVM 默认的异常处理机制,就是调用printStackTrace方法
//打印异常的堆栈的跟踪信息
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.toString());
System.out.println("jiaobiao越界");
}
System.out.println("end");
//byte[] arr =new byte[1024*1024*341];//在内存分配了341M,
//Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
}
}
复制代码
作者:
dark_lin
时间:
2014-4-2 22:33
学习了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2