In java for handling exceptions we have seen the uses of try-catch block. Now we will see that how can we throws exceptions.

First understand what’s the difference between ‘throw’ and ‘throws’ keyword.

ThrowThrows
We can throws ‘exception object’ explicitly.We can declare an exception as well as throws ‘exception object’.
Handle one exception at a time.Handle multiple exception at a time.
Followed by an exception.Followed by a class.

Throw keyword

Let’s see uses of throw keyword by some examples…

class throw1{
    public static void main(String[] args) {
        int n=2;
        if (n==2) {
            System.out.println(“block execute”);
 
            throw new ArithmeticException(“integer 10 can’t divisible by 0”);
        } 
 
    }
}
output
class throw2 { 
    public static void Num(int num) { 
        if (num < 1) { 
            throw new ArithmeticException(“\nNumber is negative, cannot calculate square”); 
        } 
        else { 
            System.out.println(“Square of ” + num + ” is ” + (num*num)); 
        } 
    } 
    public static void main(String[] args) { 
            throw2 ob1 = new throw2(); 
            ob1.Num(3); 
            System.out.println(“Rest of the code..”); 
    } 
output

Throws keyword

Let’s see uses of throw keyword by some examples…

public class throws1 { 
 
    public static int dibNum(int m, int n) throws ArithmeticException { 
        int div = m / n; 
        return div; 
    } 
 
    public static void main(String[] args) { 
        throws1 ob1 = new throws1(); 
        try { 
            System.out.println(ob1.dibNum(45, 0)); 
        } 
        catch (ArithmeticException e){ 
            System.out.println(“\nNumber cannot be divided by 0”); 
        } 
 
        System.out.println(“Rest of the code..”); 
    } 
output