Distinguish exceptions of the same type

For example, an exception of the type: java.net.BindException may cause an "already used address" (attempt to bind a port that another program uses) or "Permission denied" (you do not have access rights to open this port number) .I does not belong to the class, which throws a BindException.

So what is the best practice to distinguish between these β€œdifferent” exceptions with the same type?

I am doing this, but I do not know if this is the 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(); } 
+7
java exception
source share
1 answer

It depends. If this is the code that you have or have access to, and the BindException is not suitable, you must create your own exceptions:

 public class PermissionDeniedException 

You can 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 BindException and expect that you will behave in a certain way when an exception is thrown (i.e. just continue or always try again) OR this The problem is in the SDK. If it comes later, and this project is open source, I would recommend creating a migration request.

Otherwise, the third option, of course, will do the same as your case ... but I would not recommend it at all, since it is extremely fragile and can only change by changing the message.

+5
source share

All Articles