Throw:
- It is a keyword.
- It is used to throw an exception object explicitly by the programmer.
- Pre-defined exceptions will be raised(thrown) by JVM automatically.
- Custom exception must be raised manually by the programmer.
- If we don’t handle the exception, object will be submit to “Default Exception Handler” program.
class CustomException extends RuntimeException
{
CustomException(String name)
{
super(name);
}
}
class ThrowException
{
public static void main(String args[])
{
CustomException obj = new CustomException("Error-Message");
throw obj ;
}
}
- In the above code, custom exception is Runtime Exception
- Compiler will not provide any error in case of not handling Runtime Exceptions.
- Runtime Exception handling is optional but recommended to provide formal messages to end user..
Custom checked Exception:
- Extending from Exception class.
- Handling is mandatory.
- Compiler raises error if we don’t handle exception.
class CustomException extends Exception
{
CustomException(String name)
{
super(name);
}
}
class ThrowException
{
public static void main(String args[])
{
CustomException obj = new CustomException("Error-Message");
throw obj ;
}
}