异常分析

 

一、请阅读并运行AboutException.java示例,然后通过后面的几页PPT了解Java中实现异常处理的基础知识。

(1)源代码;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)j截图:

二、阅读以下代码(CatchWho.java),写出程序运行结果:

1)源代码: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"); 

        } 

    } 

}

(2)结果:

1)源代码:public class CatchWho2 { 

    public static void main(String[] args) { 

        try {

             try { 

                 throw new ArrayIndexOutOfBoundsException(); 

             } 

             catch(ArithmeticException 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"); 

        } 

    } 

}

(2)结果:   

三、当有多个嵌套的trycatchfinally时,要特别注意finally的执行时机。

当有多层嵌套的finally时,异常在不同的层次抛出 ,在不同的位置抛出,可能会导致不同的finally语句块执行顺序。

finally语句块一定执行

四、编写一个程序,此程序在运行时要求用户输入一个 整数,代表某门课的考试成绩,程序接着给出“不及格”、“及格”、“中”、“良”、“优”的结论。

要求程序必须具备足够的健壮性,不管用户输入什 么样的内容,都不会崩溃。

源代码:package dijia;

import java.util.Scanner;

 

public class Test {

 

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

 

double chengji;String b;

 

try{

 b = s.next();

throw new ArithmeticException(); 

 

}

catch(ArithmeticException e){

System.out.println("不及格、及格、中、良、优");

}

 

}

 

}

(1)

(2)截图;                     

 

                               

原文地址:https://www.cnblogs.com/anheidijia-123/p/6103213.html