实验04,我们学到了异常处理的有关知识

 

1.

import javax.swing.JOptionPane;

public class AboutException {
    public static void main(String[] a) 
       {
          int i=1, j=0, k;
          k=i/j;                    // 1/0 不合法


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

其输出结果为:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at ketangceshi.AboutException.main(AboutException.java:8)

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

 

JDK中与异常相关的类

为什么整型数除以0出现错误,而浮点数除以0得无穷大?

java自动把0转化为0.0  浮点数并不精确,所以结果并不属于arithmetic异常除法指令:idiv、ldiv、fdiv、ddiv

多层异常捕获

内层try抛出第一个异常时,程序控制流程跳转到内层的catch语句,解决掉了抛出的第一个异常,此时继续执行外层的try语句块内容,抛出了第二个异常(ArithmeticException),此时按异常类型选择执行catch语句块内容。内层try抛出异常后,内层的catch语句块无法解决抛出的异常,所以跳转到了外层的catch语句块,解决完异常后没有了后续的语句,所以程序结束。

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");
        }
    }
}
复制代码

当程序退出后,即    System.exit(0);语句执行后,finally语句块的内容就不会再被执行了,而是直接退出了程序。

 

posted on 2018-11-12 19:41  金猫大帝  阅读(117)  评论(0编辑  收藏  举报