zoukankan      html  css  js  c++  java
  • Java异常处理——受控(checked)的异常(throws语句)

    受控与不受控的异常

    1.throws语句中声明的异常称为受控(checked)的异常,通常直接派生自Exception类。

    2.RuntimeException(其基类为Exception) 和Error(基类为Throwable)称为非受控的异常。这种异常不用在throws语句中声明。

    throws 语句

    1.throws语句表明某方法中可能出现某种(或多种)异常,但它自己不能处理这些异常,而需要由调用者来处理。

    2.当一个方法包含throws子句时,需要在调用此方法的代码中使用try/catch/finally进行捕获,或者是重新对其进行声明,否则编译时报错。

    示例程序

     1 import java.io.*;
     2 public class ThrowMultiExceptionsDemo { 
     3     public static void main(String[] args) 
     4         { 
     5       try { 
     6             throwsTest(); 
     7        } 
     8         catch(IOException e) { 
     9             System.out.println("捕捉异常"); 
    10         }
    11     }
    12 
    13     private static void throwsTest()  throws ArithmeticException,IOException { 
    14         System.out.println("这只是一个测试"); 
    15         // 程序处理过程假设发生异常
    16         throw new IOException(); 
    17         //throw new ArithmeticException(); 
    18     } 
    19 }

    结果截图

    注:

    一个方法可以声明抛出多个异常,例如 int g(float h) throws OneException,TwoException { …… }

    当一个方法声明抛出多个异常时,在此方法调用语句处只要catch其中任何一个异常,代码就可以顺利编译。

  • 相关阅读:
    WebDriver Api
    Web系统基础
    python自动化测试相关资料
    持续集成Jenkins
    Git和Github库详细使用教程
    TCP/UDP协议
    CentOS连接网络设置
    Web测试基本思路:UI测试、功能测试和兼容性测试
    初识Jenkins
    selenium +python 对table的操作
  • 原文地址:https://www.cnblogs.com/weipinggong/p/4962496.html
Copyright © 2011-2022 走看看