Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

distinguish exceptions of same type

Tags:

java

exception

For example, the exception of type: java.net.BindException can throw a "Address already in use" (trying to bind a port that another program uses) or "Permission denied" (you do not have root permissions to open this port number).I do not own the class who throws BindException.

So, what is the best practice of distinguish these "different" Exceptions with the same type?

I am doing this, but I do not know if is a best practice:

try {
   //...some scary stuffs here  
 }
catch (BindException e){
            if (e.getMessage().contentEquals("Permission denied")){
                System.out.println("ERROR**You must be ROOT to bind that port address TCP:"+defaultPort);
            }
            else if (e.getMessage().contentEquals("Address already in use")){
                System.out.println("ERROR**Port TCP:"+defaultPort+" already in use by onother application");
            }
            e.printStackTrace();
        }
like image 202
G Bisconcini Avatar asked Jan 20 '15 18:01

G Bisconcini


1 Answers

That depends. If this is code you own or have access to and a BindException is not appropriate then you should create your own exceptions:

public class PermissionDeniedException

You could even do:

public class PermissionDeniedBindException extends BindException 

However, if this is not your class, then either the library you are using does not want you to distinguish between BindException's and is expecting you to behave in some generic manner when receiving the exception (ie just continuing or always trying again) OR this is an issue in the SDK. If the later is the case and this project is open source, I would recommend creating a pull request.

Otherwise, the third option is of course to do exactly as your are doing...but I would not recommend that at all as it is extremely fragile and could change just by modifying the message.

like image 102
stevebot Avatar answered Sep 19 '22 01:09

stevebot