Trying to create my own Java checked exception

Asked

Viewed 64 times

-1

inserir a descrição da imagem aqui

Guys, my question is this::

In the file method, I really need to do this Try-catch? In my mind I wouldn’t need to since I’m declaring the throws with my class Impossibilitieaberturadearquivoexception extending from Ioexception.

Can someone explain to me why I can’t do it that way:

inserir a descrição da imagem aqui

  • Camila Cavalcante, even though the theoretical question edits the question and places the code as text, because in certain devices code in image is unreadable. See: https://pt.meta.stackoverflow.com/a/5485/137387

1 answer

1

You cannot do it in the proposed way, because the method FileInputStream is defined as follows::

public FileInputStream(String name) throws FileNotFoundException {
    this(name != null ? new File(name) : null);
}

So in the code that calls the method FileInputStream it is mandatory to treat the exception with try/catch or pass the exception explicitly in the method declaration.

Dealing with Try/catch

public static void abreArquivo2(String nomeArquivo) throws ImpossibilitadaAberturaDeArquivoException {
    try {
        InputStream is = new FileInputStream(nomeArquivo);
    } catch (Exception e) {
        throw new ImpossibilitadaAberturaDeArquivoException (nomeArquivo, e.getCause());
    }
}

You can adjust your method with Try/catch to launch from there your custom exception. In your case, is launching at all times an exception as is not using the expression try/catch.

Flipping to be treated by the calling method

public static void abreArquivo(String nomeArquivo) throws FileNotFoundException {
    InputStream is = new FileInputStream(nomeArquivo);
}

Must include throws FileNotFoundException if it has not been treated with the try/catch.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.