zoukankan      html  css  js  c++  java
  • Java中的异常处理

    一.请阅读并运行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.结果截图:

        

      

       3. 异常处理的基础知识:

    Try{

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

           }

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

              //用于处理异常的代码

           }

           finally{

              //用于“善后” 的代码

           }

        处理机制:把可能会发生错误的代码放进try语句块中。当程序检测到出现了一个错误时会抛出一个异常对象。异常处理代码会捕获并处理这个错误。catch语句块中的代码用于处理错误。当异常发生时,程序控制流程由try语句块跳转到catch语句块。不管是否有异常发生,finally语句块中的语句始终保证被执行。如果没有提供合适的异常处理代码,JVM将会结束掉整个应用程序。

    二. 阅读以下代码(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.结果截图:

        

      

      3.结果分析:内层捕捉异常结果并处理后,外层则不再捕捉该异常。

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

         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.结果截图:

      

      3.结果分析:当异常没有被处理时,无法捕获并处理新异常

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

        1.代码:

        

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

           

                }

       

         }

     

    }

       

      2.结果截图:

      3.结果分析:一抛一接,抛之后必须有一接。当有多层嵌套的finally时,异常在不同的层次抛出,在不同的位置抛出,可能会导致不同的finally语句块执行顺序。

    五. finally语句块一定会执行吗?请通过 SystemExitAndFinally.java示例程序回答上述问题

        1.代码:

      

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

           

                }

       

         }

     

     

    }

       

       2.结果截图:

      3.改后代码:

      

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

           

                }

       

         }

     

     

    }

      4.结果截图:

      5.结果分析:当try语句执行时,对应的finally语句会执行。当没有写入让系统执行退出的命令时,fanlly会执行。

    六. 请看以下代码,它们完全符合Java语法规范,但事实是它们不能通过编译

       1.代码:

      

    public class TestThrows   {

                public static void main(String[] args)     {

                       FileInputStreamfis=new      FileInputStream("a.txt");

                       }

         }     不能通过编译

      

      2.修正后的代码:

                 public class TestThrows

    {

         public static void main(String[] args)

                              throws FileNotFoundException

                {

                       FileInputStream fis = new   FileInputStream("a.txt");

                }

    }

           修正之后通过编译

      3.原因:throws语句表明某方法中可能出现某种(或多种)异常,但它自己不能处理这些异常,而需要由调用者来处理。当一个方法包含throws子句时,需要在调用此方法的代码中使用try/catch/finally进行捕获,或者是重新对其进行声明,否则编译时报错。throws语句中声明的异常称为受控(checked)的异常,通常直接派生自Exception类。

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

       1.代码:

      

    import java.util.*;

    class NumberError   extends Exception

    {

         NumberError(String a)

         {

                super(a);

         }

    }

    class NumberBeyond extends Exception

    {

         NumberBeyond(String b)

         {

                super(b);

         }

    }

    public class Level {

     

         /**

          * @param args

          */

         public static void Numbererror() throws     NumberError

         {

                throw new NumberError("");

         }

         public static void Numberbeyond()throws NumberBeyond

         {

                throw new NumberBeyond("");

         }

         public static void main(String[] args)  {

                // TODO Auto-generated method stub

                Scanner input=new Scanner(System.in);

                System.out.println("请输入分数");

     

        

                       String in=input.next();

                       int y=1;

                      

                       try

                       {

                      

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

                              {

                                            if((in.charAt(i)>'9'||in.charAt(i)<0)&&in.charAt(i)!='.')

                                                   {

                                                          Level.Numbererror();

                                                   }

                              }

        

                             

                              try

                              {    

                                     double x=Double.parseDouble(in);

                                     if(x>100.0||x<0.0)

                                     {

                                            Level.Numberbeyond();

                                            y=0;

                                     }                  

                             

     

                              if(x>0.0&&x<60.0&&y==1)

                              {

                                     System.out.println("不及格");

                              }

                              if(x>=60.0&&x<70.0&&y==1)

                              {

                                     System.out.println("及格");

                              }

                              if(x>=70.0&&x<80.0&&y==1)

                              {

                                     System.out.println("中");

                              }

                              if(x>=80&&x<90&&y==1)

                              {

                                     System.out.println("良");

                              }

                              if(x>=90&&x<=100&&y==1)

                              {

                                     System.out.println("优");

                              }

                       }

                              catch(NumberBeyond e)

                              {

                                     System.out.println("输入超出范围"+e);

                              }

                      

                }

                catch (NumberError e)

                {

                       System.out.println("应该输入数字"+e);

               

                }

                      

         }

    }

      2.结果截图:

  • 相关阅读:
    24、Index
    23、Constraint and delete
    22、design mode : Normalization
    小米8解锁bl锁一直显示未连接手机的解决办法
    unittest之测试报告系列
    Vue常见问题处理
    Docker安装Jira8
    Docker安装rabbitmq
    docker安装redis
    python3.6默认安装路径修改_centos 7 安装python3 并修改默认的python
  • 原文地址:https://www.cnblogs.com/xieshiyu/p/6101285.html
Copyright © 2011-2022 走看看