Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java throwing exception without catching it?

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)

like image 373
Pwnna Avatar asked Dec 01 '11 23:12

Pwnna


People also ask

Can we throw exception without try catch in Java?

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 thrown but not caught?

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.

Can I use throws instead of try catch?

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.

How do you throw an exception without stopping a program?

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.


2 Answers

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.

like image 98
David H. Clements Avatar answered Sep 22 '22 03:09

David H. Clements


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.

like image 45
myro Avatar answered Sep 22 '22 03:09

myro