Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are lots of exceptions bad design in Java? [closed]

I am currently wrapping a C Library in Java, making it easier to use and work within OO-Programming. The C Library uses error codes (int return value) and Out-Parameter for data manipulation. I am not necessarily a fan of error codes, so I would like to create some custom Exception classes that I can throw if my library detects an error code other than "success".

The only problem is that the amount of Exceptions that might be raised by every single method is very high (There are some error codes that can be returned from every C library function, like "Device_Not_Connected"). It has been a while since I last programmed in Java, so, I really don't know what the situation is with Exceptions in Java.

  1. Are methods that throw a lot of different exceptions bad design?
  2. Do I have to handle the exceptions, or is there a way of simply ignoring it?
  3. If I can ignore an exception, does it bubble up the call tree (like in Python for example)?
  4. Are there any alternatives to exceptions in Java besides error codes and no-ops?
like image 907
Luca Fülbier Avatar asked Jun 08 '16 12:06

Luca Fülbier


1 Answers

Are methods that throw a lot of different exceptions bad design?

If used right clearly no! An exception basically is just a possible return state which is out of the scope of the technical purpose of the method. E.g. if the method should read an value from a device null or any value should be returned using the return type. But throwing a custom DeviceNotConnectedException to state that something went wrong when you are not able to read a return value instead of simply returnung null is 100% best practice. And if 10 things can go wrong then it is okay to state 10 possible exceptions.

Do i have to handle the exceptions, or is there a way of simply ignoring it?

When you don't catch an exception you will have to declare the method it occurs in with "public void myMethod() throws MyExcp {..}" and so on in every method calling this method, that method caller and so on. If you hand it to the main-method and it's not handled there it will crash the programm.

If i can ignore an exception, does it bubble up the call tree (like in Python for example)?

See above.

Are there any alternatives to exceptions in Java besides error codes and no-ops?

Not as far as I know but I'm not an expert.

like image 55
carrybit Avatar answered Oct 07 '22 01:10

carrybit