动手动脑9

1.请阅读并运行AboutException.java示例,然后通过后面的几页PPT了解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");
     }
        
  }
}

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

基本格式:

Try{
   //可能发生运行错误的代码;
  }
  catch(异常类型     异常对象引用){
   //用于处理异常的代码
  }
  finally{
   //用于“善后” 的代码
  }

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

2.阅读以下代码(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"); 
        } 
    } 
}
 

写出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的执行时机。

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

3.辨析:finally语句块一定会执行吗?

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.

当程序中出现异常时,JVM会依据方法调用顺序依次查找有关的错误处理程序。
可使用printStackTrace 和 getMessage方法了解异常发生的情况:
printStackTrace:打印方法调用堆栈。
每个Throwable类的对象都有一个getMessage方法,它返回一个字串,这个字串是在Exception构造函数中传入的,通常让这一字串包含特定异常的相关信息。

// UsingExceptions.java
// Demonstrating the getMessage and printStackTrace
// methods inherited into all exception classes.
public class PrintExceptionStack {
   public static void main( String args[] )
   {
      try {
         method1();
      }
      catch ( Exception e ) {
         System.err.println( e.getMessage() + "
" );
         e.printStackTrace();
      }
   }

   public static void method1() throws Exception
   {
      method2();
   }

   public static void method2() throws Exception
   {
      method3();
   }

   public static void method3() throws Exception
   {
      throw new Exception( "Exception thrown in method3" );
   }
}

 5.自定义异常通常选择直接派生自Exception:

Class MyException extends Exception
 { …    }

在合适的地方使用throw语句抛出自定义异常对象:

Class MyClass {
  void someMethod() {
   if (条件) throw new MyException();
  }
 }

在实际开发中,选择正确的异常处理策略非常重要 ,它是系统健壮性的重要保证。
在长期的软件开发实践中,人们己经总结出了多种 切实可行的异常处理方法和策略,在本讲中,我们介绍一种被广泛使用的异常处理方法——通过自定义异常类捕获并处理业务逻辑错误 。

6.

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

package com.minirisoft;
import javax.swing.*;

class ErrorException extends Exception
{
    ErrorException(String s){
        super(s);
    }

}

public class Test {
    public static void main (String[] args){
    String str1=JOptionPane.showInputDialog("请输入一个整数");
    try{
        boolean flag=true;
        char a[]=new char[100];
        for(int i=0;i<str1.length();i++)
        {
            if(str1.charAt(i)<'0'||str1.charAt(i)>'9'){
                flag=false;
            }
        }
        if(flag=false)
        {
            throw new ErrorException("输入的不是正整数");
        }
    }
    catch(ErrorException e)
    {
        e.printStackTrace();
        System.out.print("你输入的数不合法");
    }
    finally
    {
        double a=Double.parseDouble(str1);
    
    if(a>0&&a<60)
    {
        System.out.println("不及格");
    }
    else if(a>=60&&a<70)
    {
        System.out.println("及格");
    }
    else if(a>=70&&a<80)
    {
        System.out.println("中");
    }
    else if(a>=80&&a<90)
    {
        System.out.println("良");
    }
    else if(a>=90&&a<=100)
    {
        System.out.println("优");
    }
    else{
        System.out.println("你输入的数错误");
    }
    
    }
}
}
原文地址:https://www.cnblogs.com/youzeshuang/p/6103043.html