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
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.