Throw


Throw

The throw statement can be used to create a custom error. It is used together with an exception type. We can throw any of the types of exceptions using throw keyword.

Syntax:

throw new exception;

Some points to remember about the throws keyword:

  • The keyword throws are needed only for checked exceptions, and the method of throws keywords for the unchecked exception is meaningless.
  • The keyword throws are needed only to satisfy the compiler, and usage of the throws keyword does not restrict the abnormal termination of the program.
  • With the use of the keyword throws, we can give the caller information on the exception.

To prevent the compile-time error in Java, we can check the exception in two ways:

  • With the try-catch
  • Or with the throws keyword

The programmer uses the throws keyword to delegate the efficiency of exception handling to the caller (It might be one method or JVM). Then, the caller method is obliged to handle that exception. 
The keyword throw is essentially practised to throw custom exceptions as we can throw both checked or unchecked exceptions. The keyword throw in Java is practised to explicitly throw an exception from one method or any piece of code.
The keyword throw in Java is used in the sign of the method to show that this method may throw one of the well-known type exceptions. The caller to these methods has to manage the exception by practising a try-catch block. 

Example :

Com.knowledge2life public class Main { public static void validate(int age) { if(age>18) { throw new ArithmeticException("Knowledge2life"); } else { System.out.println("Knowledge2life1"); } } public static void main(String args[]){ validate(13); System.out.println("Website"); } }

OUTPUT:

Knowledge2life1
website