Checked Exception
The classes that extend Throwable class are known as checked exceptions. When we throw such exceptions with throw statements and we need to forward those exceptions at next level using throws statement till we reach to try-catch block. Such exceptions are checked at compile-time.
Example: IOException, SQLException etc.
Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions. Unchecked exceptions are not checked at compile-time.
Example: ArithmeticException, NullPointerException etc.
Using checked exception inside custom exception
class MyException extends Throwable
{
public String getMessage()
{
return "Message from My Exception";
}
}
public class Demo
{
public void welcome(String name)
{
if (name.length()==0) throw new MyException(); //error
}
}
Using unchecked exception inside custom exception
class YourException extends RuntimeException
{
public String getMessage()
{
return "Message from Your Exception";
}
}
public class Demo
{
public void welcome(String name)
{
if (name.length()==0) throw new YourException(); //no error
}
}
Comments
Post a Comment