首页 > 编程语言 >Java第五讲异常处理总结

Java第五讲异常处理总结

时间:2022-10-18 20:01:11浏览次数:43  
标签:总结 Exception Java MyException System try 第五 println public

1.

在运行上述代码时javac产生idiv字节码指令,在运行下面的程序时javac产生ddiv字节指令,导致了两段代码运行结果不同。

2.

 

 

 

 

 

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

/**
 * 自定义的异常类
 * @author JinXuLiang
 *
 */
class MyException extends Exception
{
    public MyException(String Message) {
        super(Message);
    }
    public MyException(String message, Throwable cause) {
        super(message, cause);
    }
     public MyException( Throwable cause) {
        super(cause);
    }

}

public class ExceptionLinkInRealWorld {
   public static void main( String args[] )
   {
      try {
         throwExceptionMethod();  //有可能抛出异常的方法调用
      }
      catch ( MyException e )
      {
         System.err.println( e.getMessage() );
         System.err.println(e.getCause().getMessage());
      }
      catch ( Exception e )
      {
         System.err.println( "Exception handled in main" );
      }
      doesNotThrowException(); //不抛出异常的方法调用
   }

   public static void throwExceptionMethod() throws MyException
   {
      
      try {
         System.out.println( "Method throwException" );

         throw new Exception("系统运行时引发的特定的异常");  // 产生了一个特定的异常
      }
      catch( Exception e )
      {
         System.err.println(
            "Exception handled in method throwException" );
         //转换为一个自定义异常,再抛出
         throw new MyException("在方法执行时出现异常",e);

         
      }
      finally {
         System.err.println(
            "Finally executed in throwException" );
      }

      // any code here would not be reached
   }

   public static void doesNotThrowException()
   {
      try {
         System.out.println( "Method doesNotThrowException" );
      }
      catch( Exception e )
      {
         System.err.println( e.toString() );
      }
      finally {
         System.err.println(
            "Finally executed in doesNotThrowException" );
      }

      System.out.println(
         "End of method doesNotThrowException" );
   }
}

 

 一般来说有两种情况finally不会运行:1.没运行到try-catch语句这里就返回了1)运行到try语句之前程序有了返回值,2)运行到try语句前程序报错,2.运行到try-catch语句了,但是没运行到finally代码块的时候,JVM就停止了在try语句运行的时候,直接把虚拟机退出了,如:System.exit(0); 

标签:总结,Exception,Java,MyException,System,try,第五,println,public
From: https://www.cnblogs.com/sgle0722/p/16803883.html

相关文章