Java Try Block: Catch Not Mandatory, Finally Can Follow

Respondido usando: GPT-4o-mini porJava Q&A Hub

Pergunta:

In Java Is it mandatory for a catch block to be followed after a try block?

Resposta:

In Java, it is not mandatory for a catch block to follow a try block. A try block can be followed by a finally block instead. The finally block is used to execute code that must run regardless of whether an exception was thrown or caught.

Here are the possible combinations of try blocks in Java:

  1. Try with Catch:

    try {
        // code that may throw an exception
    } catch (ExceptionType e) {
        // code to handle the exception
    }
    
  2. Try with Finally:

    try {
        // code that may throw an exception
    } finally {
        // code that will always execute
    }
    
  3. Try with Catch and Finally:

    try {
        // code that may throw an exception
    } catch (ExceptionType e) {
        // code to handle the exception
    } finally {
        // code that will always execute
    }
    

In summary, a try block can exist without a catch block, as long as it is followed by a finally block. However, if you only have a catch block, it must be preceded by a try block.