Вопрос

I was studying the Exception chapter in java and wondering if it does any good to put some throws UncheckedException after a method signature. I can see that with checked exceptions that kind of a statement is necessary to compile the code and with try, catch and finally all exceptions can be handled. But my question is what difference if at all does it make to add a throws UncheckedException after a method signature? for example, to compile the following code with a File object, you need to have a checked exception:

void main(String args[])throws IOException{
    File f=new File("c:\\java\\xyz.txt");
}

But what effect such a statement has in the following code:

public static int method1(String str)throws NumberFormatException{
    int i=Integer.parseInt(str);
    return i;
}

thanks in advance.

Это было полезно?

Решение

Adding a throws clause with an UncheckedException is only for documentation purposes, it has no functional effect.
However, this definitely makes sense in certain situations. The usual reason to do this is if you expect someone else to use your class, and you want to make it clear that your method might throw a certain Exception.

Другие советы

writing throws means the function well not handle the exception, but well give you the honor.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top