Two exceptions in Java (Checked exceptions and unchecked exceptions)

Source: Internet
Author: User

Two types of exceptions are defined in Java
    1. Checked exceptions:checked exceptions inherits from the exception class, calling client code that throws this exception API must handle the lead, otherwise it cannot be compiled, The exception is either caught by a catch clause or continues to be thrown through the throws clause. such as: SQLException
    2. Unchecked Exceptions:runtimeexception is also inherited from the exception class, however all exceptions inherited from RuntimeException are treated specially, and this type exception must be handled without requiring the client to call. such as: NullPointerException, arrayindexoutofboundexception
Checked exceptions

Exceptiontester class

package cn.sehzh;public class ExceptionTester { public void testException() throws Exception { throw new Exception("异常"); }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

Main class

package cn.sehzh;public class Main {    public static void main(String[] args) { ExceptionTester exceptionTester = new ExceptionTester(); try { //客户端调用时必须捕获或抛出,这里采用捕获 exceptionTester.testException(); } catch (Exception e) { e.printStackTrace(); } }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
Unchecked exceptions

Exceptiontester class

package cn.sehzh;public class ExceptionTester {    public void testException(){ throw new RuntimeException("运行时异常"); }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

Main class

package cn.sehzh;public class Main {    public static void main(String[] args) { ExceptionTester exceptionTester = new ExceptionTester(); //这里没有要求客户端调用时必须处理 exceptionTester.testException(); }}

Two exceptions in Java (Checked exceptions and unchecked exceptions)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.