문제

This is my code

static void tryit() throws Exception
{
      System.out.println(10 / 0);
}

public static void main(String[] args) 
{
    try {
        tryit();

    } catch (Exception e) {
        System.out.println("Exception caught in main");
    }
}

here what am wandering is, in line 1 of this code throws Exception what exactly does?
Even if I didn't use that also I got same output as

Output : Exception caught in main

Where it will be effective? Is it necessary in this code?

도움이 되었습니까?

해결책 2

here what am wandering is, in line 1 of this code "throws Exception" what exactly does?

It gave the responsibility to the caller of the function, that, this method, can throws an Exception, You [Caller] have to handle it.

And, In your case, It's a RuntimeException will be thrown from that method, so, no need to declare the method with Exception. That's why even though if you removed that throws Exception part, It works.

If the method will throw a checked Exception, and if you don't handle it inside the method itself, you have declare to throw that exception in the method signature.

다른 팁

You don't need to throws Exception in this case because ArithmeticException is a RuntimeException, the compiler doesn't know it'll be thrown, so it doesn't force you to deal with it. See:

enter image description here

Cases where you should do that, if you have an exception that's not a runtime exception, and you don't surround the line that might throw the exception with try-catch clause, then you'll have to declare the method to be throws ThatException.

"throws" is used in the signature of a method to inform the "parent method/method which calls this function" that this function "might" throw an exception, and the "parent" method/caller should handle it. And yes, as @maroun Maroun puts it, "in the current case, throws is unncesssary"

in line 1 of this code "throws Exception" what exactly does?

throws keyword tells the compiler that method with throws keyword having exceptional condition and it is not going to handle that exception. It is the responsibility of any method who called the method with throws keyword to handle that exception.

In you case tryit()throws Exception not handling the exceptional condition. In main you have called tryIt() so it is the responsibility of main to handle the unhandle exception of tryIt()throws Exception.

Where it will be effective? Is it necessary in this code?

It is effective when you want your method to be called using proper try catch(Checked type of exception).

It is not necessary in this code because in your code you are getting java.lang.ArithmeticException: / by zero exception which is RuntimeException(Un Checked type) compiler won't complain about not handling it.

for more information in checked and unchecked exception see Checked and Unchecked Exception

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top