Correct use posture for Java exceptions

Source: Internet
Author: User
Tags throwable

What are the consequences of encountering abnormal abuses in the project code recently?

1. Code readability is poor, business logic is difficult to understand

The exception flow is mixed with the business state flow and cannot understand the business code from the interface protocol level, only into the method inside to understand the behavior of the return value accurately

You can look at the code:

   public UserProfile findByID(long user_id) {Map<String, Object> cond = new HashMap<String, Object>();cond.put("id", user_id);UserProfile userInfo = null;try {userInfo = DBUtil.selecta(UserProfile.class, "user_info", cond);} catch (Throwable e) {log.error(e, "UserProfile findByID");}return userInfo;}

The DAO layer is responsible for the basic operation of the database, which returns values for the query result user object data. The code forcibly grabs all the exceptions and returns them as null, and later the person cannot confirm that NULL represents the user's absence or exception.

2. Code robustness is poor, abnormal information is randomly captured, even eaten

Similarly the above code, first grabbed the throwable this all exceptions, including error (the following will introduce the anomaly system). The code inside hides the problem, just print a line of logs, and let the program can continue to go backward, the uncertainty and risk are very large, which also greatly affect the robustness of the code.

3. The principle of a clear hierarchy of disruptive structures and a single responsibility is a major impediment to system expansion

With the development of the system, some platform systems, such as call monitoring, are often precipitated. will be responsible for the unified acquisition system of all kinds of information, because such error exception processing, it will be difficult to unify the separation of abnormal information.

So how do we actually write code that correctly considers the use of exceptions?

First, understand the design of the Java exception.

Exceptions is the customary-on-the-indicate to a calling method, a abnormal condition has occurred. A very important concept--the abnormal situation. Java exceptions are designed to handle the unusual condition of a method invocation, but how do we understand the "abnormal situation"?

Look, the JDK defines the following exception system for us:

The root node is Throwable, which represents all the exceptions in Java that can catch the inheritance of this, there are two classes down, exception and error, the daily use of more is exception,error generally left to the JDK internal use, For example, memory overflow outofmemoryerror, this kind of serious problem, the application process can not do anything, only terminate. Users seize this kind of error, generally unable to deal with, as soon as possible to terminate the safest way is often, since nothing can be done there is no need to seize. Exception is the application code to focus on, which is divided into runtime exception runtimeexception and compile-time exceptions, the respective distinction is not detailed.

After understanding the structure of the exception, the following two important issues are resolved, when to throw exceptions and what exceptions, when to catch anomalies and catch what anomalies when the exception is thrown, summed up there are three typical scenarios:

    1. The caller (Client) broke the protocol

      To be blunt is to call the method when not in accordance with the agreed specifications to pass parameters, typically such as the parameter is a non-empty set but passed in a null value. This kind of destruction protocol can also be subdivided into two categories, the caller from the interface form is not easily aware of the rules but need to give callers some strong hints, with some information up, when the exception is particularly good way, the other is the caller can clearly see the rules, normal situation will normally deal with the protocol, will not cause damage, However, the protocol may be compromised due to a bug.

    Public void  method (string[] args)  {int temperature = 0; if (Args.length > 0) {try {temperature = Integer.parseint (Args[0]);} catch (NumberFormatException e) {throw new illegalargumentexception ( "must enter integer as first Argument, args[0]= "+args[0],e"; }} //other code}            

Required to pass in an integer, but an error occurred while converting a number, a specific exception can be thrown with a hint message

    1. Know a problem, but can't handle it

      There is a "problem" here, it may be that the caller broke the protocol, but it is proposed separately to be considered from the callee, such as the method inside the read file operation, but found that the file does not exist

Public Static void Main(string[] args if (args.length = 0) {System.< Span class= "Hljs-keyword" >out.println ( "must give filename as first arg."); return; } fileinputstream in = null; try {in = new FileInputStream ( Args[0]); } catch (FileNotFoundException e) {system. Out.println ( "Can ' t" Find file: "+ args[0]); return;} //other code}             
FileInputStream在创建时抛出了FileNotFoundException,显然出现该问题时FileInputStream是处理不了的。
    1. A situation that cannot be expected

      Null pointer exceptions, array out-of-bounds are typical scenarios, typically due to a code branch being ignored

      Know when an exception occurs, but do you want to choose a compile-time exception or a run-time exception when you need to throw an exception? A lot of people might say, it's simple, it takes a caller catch on compile time, otherwise run time. The question comes, when do I need a caller catch?

      Analyzing the effects of compile-time and run-time on code writing can be summed up in the following points: whether the caller can handle, the severity, the likelihood of appearing.

      The caller can handle compile-time

      The caller cannot process the run-time

      High severity-run time

      Low probability of occurrence run-time

      I have refined this classification to consider the following process:

      Starting from the caller, if the caller breaks the protocol, throws a run-time exception, which generally appears less likely and is known to the caller, so there is no need to force the caller to catch the exception.

      Then if the problem occurs to the callee, unable to perform the work properly, this time consider whether the caller can handle the problem, if it can be processed, such as the file is not found, the network timeout, then throw a compile-time exception, otherwise such as disk full, throw run-time exception

      Resolves when exceptions are thrown and what exceptions are thrown, and then when the code that has the exception is called, what are the catch and catch exceptions? Offense and defense do not separate ... Inevitably vulgar, summed up a few points for everyone to discuss:

    2. Do not catch throwable easily, the diagram of trouble may bring great hidden danger

try {   someMethod();} catch (Throwable e) {   log.error("method has failed", e);}
 
应该尽量只去抓关注的异常,明确catch的都是什么具体的异常
    1. I can't handle it, don't catch it.

      For example, the above db may be abnormal, in the DAO layer is not able to handle this problem, the upper layer processing. Catch abnormal should not be early, throw abnormal should be too late.

    2. Avoid grasping, and the abnormal swallowed, leaving no trace

      It's not a good habit to catch an exception and play a log.

    3. Don't catch the anomaly. Mix the exception state stream with the business state flow so you're completely abandoning Java's exception mechanism

Oschina Location: https://my.oschina.net/yaohonv/blog/1603551

Correct use posture for Java exceptions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.