Throw vs throws

The throw and throws are the concepts of exception handling in Java where the throw keyword throws the exception explicitly from a method or a block of code, whereas the throws keyword is used in the signature of the method.

Some of the differences between throw and throws

THROWTHROWS
A throw is used to throw an exception explicitlyA throws to declare one or more exceptions, separated by commas.
Can throw a single exception using throwMultiple can be thrown using Throws
Only unchecked exceptions propagated using the throw keyword.propagated using the throw keyword. To raise an exception throws keyword followed by the class name and checked exception can be propagated.
The throw keyword is followed by the instance variableThrows keyword is followed by the exception class
It is used within the method.It is used with the method signature.


thow in Java

Exampe:

Java

package com.prac;

public class ThrowExample {
    public static void main(String[] args) {

        try {
            int arr[] = { 1, 2, 3, 4 };
            int x = arr[4];
        } catch (Exception e) {
            throw new ArrayIndexOutOfBoundsException();
        }
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at com.prac.ThrowExample.main(ThrowExample.java:10)


throws in Java

Example

Java

package com.prac;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ThrowsException {
    public static void main(String[] args)
throws FileNotFoundException {
        readFile();
    }

    public static void readFile() throws FileNotFoundException {
        String fileName = "file";
        File file = new File(fileName);
        @SuppressWarnings({ "unused", "resource" })
        FileInputStream stream = new FileInputStream(file);
    }
}

Output

Exception in thread "main" java.io.FileNotFoundException: file (The system cannot find the file specified) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:211) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:153) at com.prac.ThrowsException.readFile(ThrowsException.java:16) at com.prac.ThrowsException.main(ThrowsException.java:9)



No comments:

Post a Comment