Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a method that always throws an exception?

I have a method like:

int f() {   try {     int i = process();     return i;   } catch(Exception ex) {     ThrowSpecificFault(ex);   } } 

This produces a compiler error, "not all code paths return a value". But in my case ThrowSpecificFault() will always throw (the appropriate) exception. So I am forced to a put a return value at the end but this is ugly.

The purpose of this pattern in the first place is because "process()" is a call to an external web service but need to translate a variety of different exceptions to match a client's expected interface (~facade pattern I suppose).

Any cleaner way to do this?

like image 649
noctonura Avatar asked Oct 08 '10 17:10

noctonura


People also ask

How do you declare a method that throws an exception?

To specify that writeList can throw two exceptions, add a throws clause to the method declaration for the writeList method. The throws clause comprises the throws keyword followed by a comma-separated list of all the exceptions thrown by that method.

Can we declare exception in main method?

The main method is designed to catch and handle all types of exceptions.Is incorrect as JVM doesn't handle unchecked exceptions.

Why do methods have to declare the exceptions they can throw?

If the programmer did not declare that the method (might) throw an exception (or if Java did not have the ability to declare it), the compiler could not know and it would be up to the future user of the method to know about, catch and handle any exceptions the method might throw.

When should a method throw an exception?

In short: You should throw an exception if a method is not able to do the task it is supposed to do.


2 Answers

I suggest that you convert ThrowSpecificFault(ex) to throw SpecificFault(ex); the SpecificFault method would return the exception object to be thrown rather than throwing it itself. Much cleaner.

This is the pattern recommended by Microsoft's guidelines.

like image 151
CesarGon Avatar answered Sep 22 '22 07:09

CesarGon


Right now a return type can be a type, or "void" meaning "no return type". We could in theory add a second special return type "never", which has the semantics you want. The end point of an expression statement consisting of a call to a "never" returning method would be considered unreachable, and so it would be legal in every context in C# in which a "goto", "throw" or "return" is legal.

It is highly unlikely that this will be added to the type system now, ten years in. Next time you design a type system from scratch, remember to include a "never" type.

like image 31
Eric Lippert Avatar answered Sep 21 '22 07:09

Eric Lippert