This page topics close

The Java throw keyword is used to explicitly throw an exception .
So far, you have only been catching exceptions that are thrown by the Java run-time system. However, it is possible for your program to throw an exception explicitly, using the throw statement

We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception. We will see custom exceptions later.

  • how to use throw keyword

    Syntax:

    throw exceptionObject;
    

    Example)
    drag_handle
     class Example {
        public static void main(String arr[]) { 
             System.out.println("Start..");
                try
                {
                    System.out.println("Going to throw exception");
                    ArithmeticException ob=new ArithmeticException("This is Exception thrown by me");
                   
                    throw ob; //throwing exception 
    
                }catch(ArithmeticException e)
                {
                    System.out.println("Please don' t divide a number by 0");
                    e.printStackTrace();
                }   
                
             System.out.println("rest of the code ......");
             System.out.println("End..");
        }        
    }
    Output:
    Start..
    Going to throw exception
    Please don' t divide a number by 0
    java.lang.ArithmeticException: This is Exception thrown by me
    	at Example.main(Test.java:9)
    rest of the code ......
    End..
    

What next?

The next topic is throws keyword in java

Share this page