how to use throws Exception? [closed]

Solution 1:

throws Exception is used when defining a method to signal that this method may throw an error in case something does not go right. It is simply a signal, it does not handle anything.

In case you add this to a method declaration, wherever you call this method, you will be required (by the IDE, compiler..) to add handling mechanisms, such as a try-catch clause, or add yet another throws Exception to the declaration of the method that is calling your "dangerous" method.

Example:

public void dangerousMethod() throws Exception, RuntimeException // Or whatever other exception
{
    throw new Exception("FAKE BUT DANGEROUS");
}
public void anotherMethod()
{
    dangerousMethod(); // <------------ Compiler, IDE will complain that this should be handled in some way
    
    
    // Either add try catch:
    
    try
    {
        dangerousMethod();
    }
    catch(Exception e) // Or whatever specific Exception you have
    {
        // Handle it...
    }
    
    
    // Or add the throws Exception at the head of the anotherMethod()
}

Solution 2:

For unchecked exception:

NumberFormatException is a RuntimeException, which is an "unchecked exception", that means even if you don't try...catch it, it will eventually thrown to the outside (the caller).

In the outside (the caller), you can try...catch it if you want so, or you can ignore it. If the exception happens, it will be thrown out. If your program is a console program, it will be thrown and displays in the console window.

That also means your main method don't have to explicitly try..catch or throws it, and the compiler will still compile it successfully.

For checked exception:

On the other side, about the "checked exception", you have to try..catch or else the compiler will show you errors. If you do not want to try...catch the exception in the current method, you can use throws Exception in the method signature. For e.g with IOException:

public Person inputPersonInfo (String name, String address, Double salary) throws IOException {}

In your main method that is calling the above inputPersonInfo(), you have to try..catch or throws it in the main method signature.

For e.g: with IOException (a checked exception)

public static void main(String[] args) throws IOException {
    ...
    inputPersonInfo(...);
    ...
}