JavaRush /Java Blog /Random EN /Common errors in exception handling
Ve4niY
Level 14

Common errors in exception handling

Published in the Random EN group
An exception is a disruption to the normal flow of execution of a Java (or any other) program. This violation can occur due to a memory access violation, division by zero, initialization problem, execution of an illegal instruction, or any other fatal error. Java is capable of handling all such unwanted scenarios gracefully, but when it comes to using these Java features by developers, several problems may arise. In this article, I am not going to discuss how Exception Handling works in Java. I assume that the reader is already familiar with the exception hierarchy, checked exceptions , unchecked exceptions , and runtime exceptions . Here we will discuss the most common mistakes that you should avoid.
Stakeholders in Exceptions
Whenever the thread of execution is interrupted, information about it must be returned to the program executor. This thread can start from the screen, from a batch task, or in any other way. All of these triggers wait for some kind of violation in the flow to transmit a message of a certain format. A screen based trigger can gently let us know that there are some technical issues and we should contact support for help and advice. Batch processes or standalone Java programs may expect the error report to appear in the form of some kind of log that is completely incomprehensible to the end user. But business people need to receive messages in a language they understand. The dreaded NullPointerException in the minds of users is very annoying. Sometimes these errors are a consequence of incorrect use of the program, but sometimes they are problems that require correction. The second important stakeholder is the person who will have to deal with the problems raised by exceptions. This person cannot observe the actual execution of the program when the exception occurs. It will rely on two things - first, information provided by the user who is having the problem, and second, some sort of log generated when an exception occurs. In addition, the person who will analyze the problem is not the same person who wrote the program, and therefore the program developer must provide enough information for the analysis. The only way of communication between the program developer and its debugger is a log. Also, sometimes due to security reasons, the log log sometimes may not contain all the actual details of the program execution when the exception occurred. Let's look at possible errors in exception handling. Some of them look pretty stupid, but there are people. who do not pay attention to them until these errors lead to problems.
Empty exception block
This is one of the most unwanted errors in exception handling. In this case, the exception is simply ignored. The solution contains nothing but a comment line to leave the exception. try{ }catch(SQLException sqe){ // do nothing } In some rare cases, such as in the final block when the database is shut down, exceptions may be thrown. In this case they can be ignored. try{ }catch(SQLException sqe){ ... ... }finally{ try{ conn.close(); }catch(Exception e){ //leave it. } }
Incorrect generalization of exception message
This point is subjective. After catching the exception, you can report it to the end user in the form of a friendly message. It is quite possible that the details of the original message will be lost when the original messages are converted into one general message. The message should convey the proper information to the end user so that when contacting the support team, the user only needs to log into the appropriate log to provide the information. try{ File file = new File(""); file.getCanonicalPath(); }catch(IOException ioe){ throw new Exception("File Processing Failed",ioe); } In a multi-tier application, each layer catches exceptions and throws a new type of exception. Sometimes it is absolutely necessary to cast an exception of a certain type: - Data Access Layer -> creates a DataAccessException - Business Implementation Layer -> creates a BusinessException - Application Service Layer -> creates an ApplicationServiceException Everything seems logical, doesn't it? Here we may have to choose between ApplicationServiceException and BusinessException since both can represent the same information. One of these exception conversions seems unnecessary.
Destroying the StackTrace class
During the process of transforming an exception into a new special type, the stack trace may disappear, making tracking down the actual cause of the exception a nightmare. In the code below you can see how a new exception is thrown without receiving any information from the original exception. try{ File file = new File(""); file.getCanonicalPath(); }catch(IOException ioe){ throw new MyException("Problem in data reading."); }
Overwriting the exception reason
Each exception message contains information about the reason for the exception. However, when a new exception is created, information about the old one may be permanently deleted. This is similar to the example above where the StackTrace may be removed due to a new exception being thrown.
No searching for specific exceptions
Sometimes developers like to play it safe when handling exceptions. Sometimes this is easy to do. But catching java.lang.Exception instead of a specific exception is not acceptable. try{ File file = new File(""); file.getCanonicalPath(); }catch(Exception exe){ throw new MyException("Problem in data reading."); }
Unnecessary catch and throw
Catch exceptions if you want to convert them to another type, or if it helps you add some information to the exception message to the end user or analyst. Otherwise, just throw them away further in the method signature (using throws) instead of catching them.
Catching RuntimeException
I would recommend avoiding catching RuntimeException. Instead, it is better to catch specific exceptions and treat them.
Finding unchecked exceptions
It is a controversial topic whether to catch unchecked exceptions or not. NullPointerException and ArrayIndexOutOfBound might be the best examples of unchecked exceptions. Instead of catching these exceptions, you can change your code to handle these scenarios. For example, to avoid NullPointerException, to ensure that all variables are initialized, to avoid ArrayIndexOutOfBound exceptions, to define an array of the correct length, etc.
Issues related to exception logging
The magazine will help the second interested person, that is, the person analyzing the problem. Sometimes a developer goes overboard with log files and logs are created at every level of the application. The log should record the exception at the level at which it occurred. It seems optimal to display a warning that an exception has occurred, with a proposal to stop or continue execution of the program, and mandatory logging of the exception in the log.
Flow control exception
An exception is a disruption to the normal flow of the program, which means that you need to interrupt this flow and inform the end user about it. If we add a method call that is an alternate thread, it will lead to huge maintenance problems. try{ myObject.getValue(); }catch(NullPointerException npe){ alternateMethod(); }
Ubiquitous use of java.lang.Exception
It is also not a good idea to use java.lang.Exception everywhere for any exception. Instead, it is better to use application-specific exceptions, or the most appropriate standard Java exceptions. Original article: Common Mistakes in Exception Handling Translated and voiced by: Ve4niY
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION