Core Java Concepts and Syntax

Learn about Throw and Throws in Java

Learn about Throw and Throws in Java

In Java, the concept of Throw and throws are useful in exception handling. A throw keyword raises an exception explicitly from a method or code block, while throws get used in a method's signature.

What is Throw in Java?

In Java, the throw keyword raises an error that the programmer defines explicitly and logically during control flow from one block to another, and the error exceptions get defined and handled appropriately.

Throw Syntax

throw <instance>;

Example

public class Throw_sample {
    public static void checkNum(int num) {
        if (num < 1) {
            throw new ArithmeticException("\nNegative Number entered , cannot calculate square");
        } else {
            System.out.println("Square of Number: " + (num*num));
        }
    }
    public static void main(String[] args) {
        Throw_sample obj = new Throw_sample();
        obj.checkNum(-5);
        System.out.println("Code End..");
    }
}


Output
Exception in thread "main" java.lang.ArithmeticException:
Negative Number entered , cannot calculate squareat Throw_sample.checkNum(Throw_sample.java:4)
at Throw_sample.main(Throw_sample.java:11)

write your code here: Coding Playground

What are Throws in Java?

This method is similar to the try-catch block in declaring and calling an exception block.

Example

public class Throws_Sample {
    public int div(int a, int b) throws ArithmeticException {
        int t = a/b;
        return t;
    }
    public static void main(String args[]) {
        Throws_Sample obj = new Throws_Sample();
        try {
            System.out.println(obj.div(5,0));
        } catch(ArithmeticException e) {
            System.out.println("Dividing by zero is not allowed");
        }
    }
}

Output
Dividing by zero is not allowed

write your code here: Coding Playground

Use of Throw and Throws in Java

A throw keyword gives the JVM an instance of an exception that the programmer has manually created, whereas a throws keyword gives the caller method responsibility for handling the exception.

Difference Between Throw And Throws

Throw

Throws

In the internal implementation of throw, only a single exception may be thrown at a time, so multiple exceptions cannot be thrown.

The throws keyword, however, allows us to declare multiple exceptions that will be thrown as a result of the function that uses it.

The throw keyword is used within the method in order to use it.

Alternatively, the throws keyword appears in the method signature.


The throw keyword cannot be used to throw checked exceptions.

Throws is used to raise checked exceptions.


Throw must be used inside any method.

The throws keyword must be used with any method sign.

Hope this article gave you a clear understanding of the concept.