Differences between Runtime/Checked/Unchecked/Error/Exception

前端 未结 8 899
走了就别回头了
走了就别回头了 2020-11-27 05:17

What are the Runtime exceptions and what are Checked/Unchecked Exceptions and difference between Error/Exception.Why these many types? Instead Java may simply follow a simpl

8条回答
  •  有刺的猬
    2020-11-27 05:43

    This article sumarizes Checked and Unchecked exceptions in a clear and concise way.

    • Checked Exceptions: Checked Exceptions are the exceptions which can be detected, identified and checked at compile time. If a code block throws a checked exception then the method must handle the exception or it must specify the exception using throws keyword.

      • Example:

        public void testDB() throws ClassNotFoundException, SQLException
        {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Driver Loaded");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/selenium","root","root");
            System.out.println("Connected to MySQL DB");
        }
        
      • We either need to specify list of exceptions using throws or we need to use try-catch{} block. I have demonstrated the useage of throws in the below program.

    • Unchecked Exceptions: Unchecked Exceptions are not checked at compiled time. Java exceptions under Error and RuntimeException classes are unchecked exceptions and everything else under throwable is checked.

    Summary: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

提交回复
热议问题