集册 Java实例教程 尝试...捕获...最终的异常处理机制。

尝试...捕获...最终的异常处理机制。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

618
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
尝试...捕获...最终的异常处理机制。

public class Main /*时 代 J a v a 提供*/

{

   public static void main(String[] args)

   {

      try 

      { 

         throwException(); 

      }

      catch (Exception exception) // exception thrown by throwException

      {

         System.err.println("Exception handled in main");

      } 


      doesNotThrowException();

   } 
   /*
    from n o w j a v a . c o m - 时代Java 
   */


   // demonstrate try...catch...finally

   public static void throwException() throws Exception

   {

      try // throw an exception and immediately catch it

      { 

         System.out.println("Method throwException");

         throw new Exception(); // generate exception

      }

      catch (Exception exception) // catch exception thrown in try

      {

         System.err.println(

            "Exception handled in method throwException");

         throw exception; // rethrow for further processing


         // code here would not be reached; would cause compilation errors


      } 

      finally // executes regardless of what occurs in try...catch

      {

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

      }


      // code here would not be reached; would cause compilation errors


   }


   // demonstrate finally when no exception occurs

   public static void doesNotThrowException()

   {

      try // try block does not throw an exception

      { 

         System.out.println("Method doesNotThrowException");

      }

      catch (Exception exception) 
展开阅读全文