Tutorials

Java Exception Handling


throw


In java throw keyword is used to throw an exception. This exception can be the one that you just caught in your code snippet or a newly instantiated one

 

Syntax


throw ExceptionObject;

Important points 

  • throw can be used to throw only one instance of exception at a time.
  • throw is always used inside the method body.
  • Any method which intends to throw an exception must use throw keyword along with the instance of Throwable class.
  • throw can be used to throw custom (or user defined) exception as well.

 

Throwable is the base of all exception classes

Example

 


package exceptionHandling;

public class ThrowExample {

      public static void main(String[] args) {

            int marks = 65;

            if(marks<70){

                  throw new ArithmeticException("Not eligible for admission");

            }

      }

}

OUTPUT:

Exception in thread "main" java.lang.ArithmeticException: Not eligible for admission
at exceptionHandling.ThrowExample.main(ThrowExample.java:9)
 

You can see here the code is explicitly throwing an Arithmetic Exception if the marks is less than 70.

 

Similarly you can also throw custom exception as well. We will learn in detail about it in custome exception section of this tutorial.



Please Share this page
Views : 84
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!