Exception Handling Using Throws keyword

Throws is a keyword used to indicate that this method could throw this type of exception.

The caller has to handle the exception using a try-catch block or propagate the exception. We can throw either checked or unchecked exceptions. We use the keyword throws to throw the checked exception up the stack to the calling method to handle.

Example 1:

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)


Example 2:

Java


import java.io.IOException;

class Testthrows {
    void m() throws IOException {
        throw new IOException("Throw exception"); // checked exception
    }

    void n() throws IOException {
        m();
    }

    void p() {
        try {
            n();
        } catch (Exception e) {
            System.out.println("exception handled");
        }
    }

    public static void main(String args[]) {
        Testthrows obj = new Testthrows();
        obj.p();
        System.out.println("normal flow...");
    }
}

Output

exception handled normal flow...


Exception Handling Using Throw keyword

Java catch Multiple Exceptions

Java try/ catch block exception handling

Exception Handling Using Throws keyword

Java nested try block exception handling

Java custom exception handling

Throw vs throws

Java finally block exception handling

Java Exception propagation

Final vs Finally vs Finalize

Exception Handling Interview Questions

No comments:

Post a Comment