zoukankan      html  css  js  c++  java
  • Java: Checked & Unchecked Exceptions

    Unchecked exceptions: Classes that are direct or indirect subclasses of RuntimeException, typically caused by defects in code. 

    E.g. ArrayIndexOutOfBoundExceptions, ArithmeticExceptons.

    Classes that inherit directly or indirectly from Error (serious abnormal situations in JVM, application program should not attempt to deal with) are unchecked, too.

    Unlike checked exceptions, Java does not examine whether an unchecked exception is caught or declared because they typically can be prevented by proper coding.

    -- Although the compiler does not enforce it, it’s still better to provide exception-handling code when it’s known that such exceptions might occur. E.g. program should handle NumberFormatException from Integer method parseInt, even though NumberFormatException is checked exception.

     

    Checked exceptions: Classes that inherit from Exception but not directly or indirectly from RuntimeException, typically caused by conditions that are not under the control of the program.

    e.g. for file processing, when the program cannot open a file that doesn’t exist.

     

    Catch-or-declare requirement: The compiler verifies that the checked exception is caught or is declared in a throws clause, an error message will be issued if it’s not satisfied.

    1) The code that generates the exception must be wrapped in a try block and must provide a catch handler for the checked-exception type (or its superclasses);

    2) The method containing the code that generates the exception must provide a throws clause containing the checked-exception type after its parameter list and before its method body. (If the exception can be handled inside the method then there’s no need to declare throws, just catch to handle it.)

    Notice: If a subclass overrides a superclass’s method, subclass method cannot list more exceptions in its throws clause than the superclass method does, but can contain a subset of the superclass’s throws clause.

  • 相关阅读:
    JUC高并发编程(三)之模拟接口压力测试
    JUC高并发编程(二)之多线程下载支付宝对账文件
    JUC高并发编程(一)之请求合并案例
    《Head First设计模式》读书笔记
    图文详解23种设计模式
    Laravel路由匹配
    深夜debug:一个不常遇到的HbuilderX自动化测试运行问题
    高德地图API中折线polyline不能跨越180度经度线的解决方案
    sublime配置java运行环境
    Docker技术入门
  • 原文地址:https://www.cnblogs.com/RDaneelOlivaw/p/11260745.html
Copyright © 2011-2022 走看看