Java Exception Encapsulation (custom error codes and descriptive narratives, with source code)

Source: Internet
Author: User

Really work before you find out. It is common to use exceptions in Java in real work.

When to throw something out of the ordinary, this must be known.

Of course, the exception that is actively thrown in the real work is a sub-loaded, and can define the error code and description of the exception.

The following small Bao will introduce you to a simple Java exception package sample.

Before the exception is given a farce example. It is necessary to popularize the concept of checked anomalies and unchecked anomalies in Java.

I. Checked anomalies and unchecked anomalies

The reason here is to let everyone know checked anomaly and unchecked anomaly concept, is because: our exception is inherited unchecked abnormal runtimeexception. There's no harm in knowing.

Checked Exception:

The expression is invalid. It is not possible to predict in a program. For example, invalid user input, file does not exist, network or database link error. These are external reasons, and are not controlled within the program.

Must be handled explicitly in the code. For example, try-catch block processing. Or add throws instructions to your method. Throws an exception to the upper layer of the call stack.

Inherit from java.lang.Exception (except Java.lang.RuntimeException).

Unchecked Exception:

Represents an error. The logic error of the program. is a subclass of runtimeexception, such as IllegalArgumentException, NullPointerException and IllegalStateException.

You do not need to explicitly capture unchecked exceptions in your code to do the processing.

Inherit from Java.lang.RuntimeException (while Java.lang.RuntimeException inherits from Java.lang.Exception).

Look at the anomaly structure below, perhaps with a deeper sense of hierarchy:

Ii. examples of abnormal loading

2.1. Add an enumeration Luoerrorcode.java such as the following:

Package Com.luo.errorcode; Public enumLuoerrorcode {null_obj ("LUO001","Object is empty"), Error_add_user ("LUO002","Join user failed"), Unknown_error ("LUO999","The system is busy, please try again later ...");PrivateStringvalue;PrivateString desc;Private Luoerrorcode(Stringvalue, String desc) { This. SetValue (value); This. SETDESC (DESC); } PublicStringGetValue() {return value; } Public void SetValue(Stringvalue) { This.value=value; } PublicStringGetDesc() {returnDesc } Public void Setdesc(String desc) { This. desc = desc; } @Override PublicStringtoString() {return "["+ This.value+"]"+ This. Desc; }}

Attention!

!!

Here we rewrite the ToString method of Luoerrorcode, as to why. The following will be mentioned, objective please continue to look.

2.2. Create an exception class Businessexception.java, Inherit runtimeexception:

package com.luo.exception;publicclass BusinessException extends RuntimeException {    privatestaticfinallong1L;    publicBusinessException(Object Obj) {        super(Obj.toString());    }}

Although the code here is short, there are two points to pay attention to!!! The 1th is that it inherits the RuntimeException. As a general rule, our business exceptions are execution-time exceptions.

2nd, here the constructor method calls the parent method super (Obj.tostring ()), this is the reason for rewriting the Luoerrorcode toString method, the assumption is not clear, you will be clear after reading.

2.3, test class Exceptiontest.java:

package com.luo.test;import com.luo.errorcode.LuoErrorCode;import com.luo.exception.BusinessException;publicclass ExceptionTest {    publicstaticvoidmain(String args[]) {        null;        ifnull){            thrownew BusinessException(LuoErrorCode.NULL_OBJ);        }    }}

Execution Result:

Add: In our actual project, for example, someone else calls you interface. You may need to see if the object he passed is not empty, and first infer that the object passed is null for a friendly hint "[LUO001] object is empty". Otherwise, a null pointer exception is expected to appear in the subsequent code.

General companies will be divided into a basic framework, abnormal distribution is part of the. Of course, their distribution of the anomaly is certainly more complicated than this example, so this example is for reference only.

If you don't bother with copy and paste, download project directly:

http://download.csdn.net/detail/u013142781/9422684

Java Exception Encapsulation (custom error codes and descriptive narratives, with source code)

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.