1.运行AboutException.java
import javax.swing.*;
class AboutException {
public static void main(String[] a)
{
int i=1, j=0, k;
k=i/j;
try
{
k = i/j; // Causes division-by-zero exception
//throw new Exception("Hello.Exception!");
}
catch ( ArithmeticException e)
{
System.out.println("被0除. "+ e.getMessage());
}
catch (Exception e)
{
if (e instanceof ArithmeticException)
System.out.println("被0除");
else
{
System.out.println(e.getMessage());
}
}
finally
{
JOptionPane.showConfirmDialog(null,"OK");
}
}
}
结果:
2.运行catchwho
public class CatchWho
{
public static void main(String[] args)
{
try
{
try
{
throw new ArrayIndexOutOfBoundsException();
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println( "ArrayIndexOutOfBoundsException" + "/内层try-catch");
}
throw new ArithmeticException();
}
catch(ArithmeticException e)
{
System.out.println("发生ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println( "ArrayIndexOutOfBoundsException" + "/外层try-catch");
}
}
}
结果:
ArrayIndexOutOfBoundsException/内层try-catch
发生ArithmeticException
3.运行catchwho2
结果:ArrayIndexOutOfBoundsException/外层try-catch
结论:多个try catch嵌套先从上到下逐层运行并抛出对应的异常
4.运行
public class EmbededFinally
{
public static void main(String args[])
{
int result;
try
{
System.out.println("in Level 1");
try
{
System.out.println("in Level 2");
// result=100/0; //Level 2
try
{
System.out.println("in Level 3");
result=100/0; //Level 3
}
catch (Exception e)
{
System.out.println("Level 3:" + e.getClass().toString());
}
finally
{
System.out.println("In Level 3 finally");
}
// result=100/0; //Level 2
}
catch (Exception e)
{
System.out.println("Level 2:" + e.getClass().toString());
}
finally
{
System.out.println("In Level 2 finally");
}
// result = 100 / 0; //level 1
}
catch (Exception e)
{
System.out.println("Level 1:" + e.getClass().toString());
}
finally
{
System.out.println("In Level 1 finally");
}
}
}
结果:
in Level 1
in Level 2
in Level 3
Level 3:class java.lang.ArithmeticException
In Level 3 finally
In Level 2 finally
In Level 1 finally
结论:异常逐层抛出,同时final语句块先结束最里层的异常再逐级往外结束。
5.运行SystemExitAndFinally.java
public class SystemExitAndFinally
{
public static void main(String[] args)
{
try
{
System.out.println("in main");
throw new Exception("Exception is thrown in main");
//System.exit(0);
}
catch(Exception e)
{
System.out.println(e.getMessage());
System.exit(0);
}
finally
{
System.out.println("in finally");
}
}
}
结果:
in main
Exception is thrown in main
结论:
catch(Exception e)
{
System.out.println(e.getMessage());
System.exit(0);
}中将System.exit(0)会退出程序导致final语句块不执行,只要不退出,final就会执行。