Throw And Throws In Java

That's_rushi
2 min readMar 27, 2023

--

Throw Statement:

Sometimes we can create Exception object explicitly and we can hand over to the JVM manually by using throw keyword. 

  • Customized exceptions are always runtime exp(unchecked). 
  • For Customized exceptions we should extend RuntimeException.

Throws Statement:

The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception. So, it is better for the programmer to provide the exception handling code so that the normal flow of the program can be maintained.

It points out specifies that may occur an exception in the method. It never throw exceptions.

Note : 

  • Hence the main objective of “throws” keyword is to delegate the responsibility of exception handling to the caller method. 
  • “throws” keyword required only checked exceptions. Usage of throws for unchecked exception there is no use. 
  • “throws” keyword required only to convince complier. Usage of throws keyword doesn’t prevent abnormal termination of the program. Hence recommended to use try-catch over throws keyword

Exception handling keywords summary:

  1. try: To maintain risky code.
  2. catch: To maintain handling code.
  3. finally: To maintain cleanup code.
  4. throw: To handover our created exception object to the JVM manually.
  5. throws: To delegate responsibility of exception handling to the caller method.

Types of Predefined Exception

  1. ArrayIndexOutOfBoundsException:

It is the child class of RuntimeException and hence it is unchecked. Raised automatically by the JVM whenever we are trying to access array element with out of range index

2. NullPointerException:

It is the child class of RuntimeException and hence it is unchecked. Raised automatically by the JVM, whenever we are trying to call any method on null.

--

--

That's_rushi

Developer with experience in application development using Java, spring boot and J2EE. Expertise in using Core Java & Web technologies like Restful Webservices.