Is it possible to throw an exception without catching it?
Example
public void foo() throws SomeException{
// ....
if (somethingCatestrophic) throw new SomeException();
// ....
}
Now I want to call foo, but don't want to catch any errors, as the exceptions should never been thrown at runtime (unless there's a bug)
Yes it is Ok to throw an exception when it isn't inside a try block. All you have do is declare that your method throws an exception. Otherwise compiler will give an error.
What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console. The message typically includes: name of exception type.
Q #2) Can we use throws, try and catch in a single method? Answer: No. You cannot throw the exception and also catch it in the same method. The exception that is declared using throws is to be handled in the calling method that calls the method that has thrown the exception.
To print an exception without exiting the program, use a try/except block and assign the exception object to variable e using except Exception as e . Now, call print(e) in the except branch to print a simple error message.
Unless it is something you are planning for and recovering from locally, it is probably best in this case to use an unchecked exception, e.g., a RuntimeException
derivative.
Why don't you catch it inside the method?
Simply use try catch block and go on, if the exception is insignificant and doesn't influence any behaviour of your program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With