06异常处理

一、异常处理

异常处理的目的是依据实际情况提供不同的错误应对策略与手段,使程序更稳定,更安全。

异常处理的主要用途是提供准确的错误消息,解释失败的原因、位置和错误类型等,同时提供一定的恢复能力,尽可能地保证数据完整性不被破坏,并让程序能继续运行。

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

源代码:

 

import javax.swing.*;

 

class AboutException {

   public static void main(String[] a)

   {

      double d1=-100,d2=0,result;

      result=d1/d2;

    try//可能发生运行错误的代码

    {

        result = d1/d2;    // 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"+result);

     }

  }

}

 

运行结果截图:

 

Java中的异常捕获语句

Try{

     //可能发生运行错误的代码;

}

catch(异常类型 异常对象引用){

     //用于处理异常的代码

}

finally{

      //用于“善后” 的代码

}

使用Java异常处理机制

1、Java 中所有可捕获的异常都派生自 Exception 类。

2、把可能会发生错误的代码放进try语句块中。

3、当程序检测到出现了一个错误时会抛出一个异常对象。异常处理代码会捕获并处理这个错误。 catch语句块中的代码用于处理错误。

4、当异常发生时,程序控制流程由try语句块跳转到catch语句块。

5、不管是否有异常发生,finally语句块中的语句始终保证被执行。

6、如果没有提供合适的异常处理代码,JVM将会结束掉整个应用程序。

【动手动脑】多层的异常捕获-1

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

 

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

写出CatchWho2.java程序运行的结果

 

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");

        }

    }

}

 

运行结果截图:

 

【动手动脑】当有多个嵌套的try…catch…finally时,要特别注意finally的执行时机。

请先阅读 EmbedFinally.java示例,再运行它,观察其输出并进行总结。

源代码:

 

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");

        }

    }

}

 

运行结果截图:

 

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

1)、只有与 finally 相对应的 try 语句块得到执行的情况下,finally 语句块才可能会执行。

2)、在 try 语句块中执行了 System.exit (0) 语句,终止了 Java 虚拟机的运行时。

3)、当一个线程在执行 try 语句块或者 catch 语句块时被打断(interrupted)或者被终止(killed),与其相对应的 finally 语句块可能不会执行。

4)、更极端的情况,就是在线程运行 try 语句块或者 catch 语句块时,突然死机或者断电,finally 语句块肯定不会执行了。

5)、不管 try 语句块正常结束还是异常结束,finally 语句块是保证要执行的。如果 try 语句块正常结束,那么在 try 语句块中的语句都执行完之后,再执行 finally 语句块。如果 try 中有控制转移语句(return、break、continue)finally 语句块在 try 或catch语句块中的 return 语句之前执行。

【动手动脑】finally语句块一定会执行吗?

请通过 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");

        }

    }

}

 

运行结果截图:

 

 至少有两种情况下finally语句是不会被执行的:
(1)try语句没有被执行到,如在try语句之前return就返回了,这样finally语句就不会执行。这也说明了finally语句被执行的必要而非充分条件是:相应的try语句一定被执行到。

(2)在try块|catch块中有System.exit(0);这样的语句。System.exit(0)是终止Java虚拟机JVM的,连JVM都停止了,所有都结束了,当然finally语句也不会被执行到。

在try-catch-finally中, 当return遇到finally,return对finally无效,即:

     1.在try catch块里return的时候,finally也会被执行。

     2.finally里的return语句会把try catch块里的return语句效果给覆盖掉。

结论:return语句并不一定都是函数的出口,执行return时,只是把return后面的值复制了一份到返回值变量里去了。

课后作业二

编写一个程序,此程序在运行时要求用户输入一个 整数,代表某门课的考试成绩,程序接着给出“不及格”、“及格”、“中”、“良”、“优”的结论。 要求程序必须具备足够的健壮性,不管用户输入什 么样的内容,都不会崩溃。

源代码:

 

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

 

package zuoye9;

import java.util.Scanner;

 

class methodException extends Exception{

    public methodException(String mas)

    {

        super(mas);

    }

   

}

public class Score {

 

    public static void main(String[] args) {

        // TODO Auto-generated method stub

 

        System.out.println("请输入英语的成绩:");

        Scanner input=new Scanner(System.in);

        String num;

        num=input.next();

        int a=0;

        while(a==0){

            try{

               

                for(int i=0;i<num.length();i++)

                {

                    if(num.charAt(i)<47||num.charAt(i)>58)

                    {

                        throw new methodException("输入不正确,请输入数字:");

                    }

                    else

                    {

                        a=1;

                    }

                }

            }

            catch(methodException e){

                System.out.println("输入不正确,请重新输入数字:");

                num=input.next();

            }

        }

        int dd=Integer.parseInt(num);

        if(dd<60)

        {

            System.out.println("你的成绩不及格!");

        }

        else if(dd>=60&&dd<70)

        {

            System.out.println("成绩及格!");

        }

        else if(dd>=70&&dd<80)

        {

            System.out.println("成绩中等!");

        }

        else if(dd>=80&&dd<90)

        {

            System.out.println("成绩良!");

        }

        else if(dd>=90)

        {

            System.out.println("成绩优异!");

        }

    }

 

}

 

运行结果截图:

 

 

 

原文地址:https://www.cnblogs.com/zhangfan0801/p/7846174.html