标签:
异常:就是程序在”运行时“出现的不正常情况。也不要简单的就书写一条输出语句。
class Arithmetic
{
int method(int a,int b) throws ArithmeticException,ArrayIndexOutOfBoundsException
{
int[] arr=new int[a]; //虽然有两个可能的异常,但是在运行时遇到第一个异常后程序就会终止运行,后面的程序不再执行。
System.out.println(arr[4]);
return a/b;
}
}
class ExceptionClassDemo
{
public static void main(String args[]) //throws Exception//在功能上通过throws的关键字声明了该功能可能会出现问题。
{
Arithmetic ar=new Arithmetic();
try
{
int result=ar.method(4,0);
System.out.println("result:"+result);
}
catch (ArithmeticException e) //Exception e = new ArithmeticException();
{
System.out.println("除数不能为零!");
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("数组越界啦");
}
System.out.println("over");
}
}标签:
原文地址:http://blog.csdn.net/iemdm1110/article/details/51356774