Sobes.tech
Junior — Middle

Is it mandatory to use a try-catch block if the called method declares throws?

sobes.tech AI

Answer from AI

If a method is declared with throws (checked exception) in Java, then when calling it, the compiler requires either handling the exception with a try-catch block or declaring throws in the signature of the calling method. Thus, using a try-catch block is not strictly mandatory, but the exception must be handled either locally or passed further.

Example:

public void readFile() throws IOException {
    // code that may throw IOException
}

public void process() {
    try {
        readFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

// or

public void process() throws IOException {
    readFile();
}

If the exception is unchecked (a subclass of RuntimeException), then a try-catch block is not required.

Is it mandatory to use a try-catch block if the… - sobes.tech