/**
* Write a description of class TestTryCatch here.
*
* @author xiaopan
* @version 1
*/
import java.io.InputStream;
import java.io.IOException;
public class TestTryCatch
{
public static void main(String[] args)
{
int[] x = {10,5,0};
try
{
System.out.println("First try block in main() entered");
//无异常出现
System.out.println("result = " + divide (x,0));
x[1] = 0;
//在divide方法 中出现算术异常
System.out.println("result = " + divide (x,0));
x[1]=1;
// divide(x,1)第二个参数
// 让该方法无法处理异常,但是会抛出异常给
// main方法,所谓的方法异常抛出机制,由调用divide()
// 的方法main()处理,看main中的
// // catch (ArrayIndexOutOfBoundsException e)
// {
// System.out.println("数组索引错误 caught in main()");
//
// }
System.out.println("result = " + divide (x,1));
}
catch (ArithmeticException e)
{
System.out.println("数学错误 caught in main()");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("数组索引错误 caught in main()");
}
System.out.println ( "Outside first try block in main ()");
System.out.println( "\nPress Enter to exit");
try
{
System.out.println ("In second try block in main()");
System.in.read();
//如果没有下面的rerun语句,那么main()最后的语句
// System.out.println("Code after second try bolck in main()");
//就会执行
return;
}
catch (IOException e)
{
System.out.println ("I/O exception caught in main()");
}
//finally语句总是要执行的,如果在try,catch语句快中有return,那么
//finally会在这样的return语句前执行,也会让finally后面的语句
//不执行。
finally {
System.out.println("fianlly block for second try block in main()");
}
System.out.println("Code after second try bolck in main()");
}
//divide子方法
public static int divide(int[] array, int index)
{
try
{
System.out.println("\n First try block in divide() entered");
array[index +2] = array[index]/array[index+1];
System.out.println("Code at end of first try block in divide()");
return array [index +2];
}
catch (ArithmeticException e)
{
System.out.println("数学错误 caught in divide()");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("数组索引错误 caught in divide()");
}
finally
{
System.out.println("finally block in divide()");
}
System.out.println("Executing code after try block in divide()");
//下面的语句如果出现异常,那么divide()方法无法处理,异常会抛出,
//由调用divide()的方法捕获,这里是main(),如果在main()中没有相应的
//处理机制程序会中断运行,但是本程序中在main()中有相应的
//catch语句,因此程序不会中断。这就是被调用方法的异常如果不在
//该方法中被处理,那么由调用它的上级方法处理,这样
//可以一直到程序的顶级方法(入口),如果在顶级方法中还是没
//有处理机制,那么程序就会中断运行
return array [index +2];
}
}