Custom Exceptions for Java exceptions

Source: Internet
Author: User
Tags throw exception throwable

Oh, mom, it's out of the ordinary again! As the saying goes: "Code abuse me times, I want to code such as First love."

Little Alan has been busy working recently, has not written something to deepen his understanding, today to talk about Java exceptions. Java exception of the system what, theoretical knowledge of what I do not bother to BB too much, is a Java development is known, but may not understand the depth of the people can see their own more information, I will simply say.

What is an exception?

I do not know how everyone is to understand, my understanding is very simple, it is not normal situation, such as I am now a man, but I have a woman's unique things, in my opinion this is a kind of strange, it can not endure. Take the above abnormal picture, you should have a small brother, but you do not have a penis, this is not normal situation, so Java this sister will tell you, you should have a small brother's ability to work, or you do not have a penis to do things, you do not have a penis is also stronger on others, that also can not play ah?

Often said that our ancestors are apes, abnormal exception ancestors that is Throwable class, in addition to exception class, Throwable also has a sub-class error. Error This thing will not say, if you meet it you can hit the computer, exhale ... Let's make a joke about it, it's not something that our program can handle, it's outside the scope of program processing. As for the abnormal exception and divided into silly what, I will not BB, and then BB on the B to the top.

Give us some random exceptions:

RuntimeException: You can't run fast enough, maybe because you're too fat. Turn off your computer and go out for exercise.

NullPointerException: You don't have a dog. Please find a dog, such as a Brittany hunting dog, and then try again.

Indexoutofboundsexception: You put your index finger where you can't receive it, re-place it, and try again.

FileNotFoundException: A carpenter should always know where to put his tools.

Notserializableexception: You're trying to change a movie into a TV show.

What the hell is this Nima? I didn't read it anyway. Fortunately today I want to understand the object is not above these things, wrong object is not good, look good, but don't mess, men understand, tut. Tut.. Tut....

Custom exceptions

Today we are going to understand what is a custom exception, why use a custom exception, what are the benefits of using a custom exception, and what are the bad things?

To use a custom exception just like you and your girlfriend, first you need to know why you are with your girlfriend, what are the benefits of your girlfriend, what are the bad places, and your girlfriend to marry a lifetime, we first say these questions, and finally see how to use custom exceptions, The implementation and use of custom exceptions is very simple, and the key is to understand why's content.

Why use custom exceptions, what are the benefits?

1. When we work, the project is sub-module or sub-function development, basically do not you develop an entire project, the use of custom exception classes to unify the presentation of external anomalies.

2. Sometimes when we encounter certain checks or problems, we need to directly end the current request, you can throw a custom exception to the end, if you are using SPRINGMVC in the project to compare the new version of the words have controller enhancements, A controller enhancement class can be written with @controlleradvice annotations to intercept custom exceptions and respond to the appropriate information for the front-end ( about SPRINGMVC Controller enhancement knowledge is available to share with you later ).

3. Custom exceptions can throw exceptions in certain special business logic in our project, such as "neutral". Equals (Sex), when gender equals neutral, we throw an exception, and Java doesn't have this exception. Some errors in the system are Java-compliant, but do not conform to the business logic of our project.

4. Using a custom exception to inherit the associated exception to throw the treated exception information can hide the underlying exception, which is more secure, and the exception information is more intuitive. Custom exceptions can throw the information we want to throw, can be thrown by the information to distinguish the location of the occurrence of the exception, according to the name of the exception we can know where there is an exception, according to the exception prompt information for program modification. For example, null pointer exception nullpointexception, we can throw the message "xxx is empty" to locate the exception location, without the output stack information.

What's the benefit of using a custom exception, let's look at the problem with custom exceptions:

There is no doubt that we cannot expect the JVM (Java Virtual machine) to automatically throw a custom exception or expect the JVM to automatically handle a custom exception. The work of discovering exceptions, throwing exceptions, and handling exceptions must be done by programmers using exception handling mechanisms in their code. This adds a number of development costs and workload accordingly, so the project is not necessary, it does not have to use the custom exception, to be able to weigh themselves.

Finally, let's take a look at how to use custom exceptions:

In Java, you can customize exceptions. Here are some things to keep in mind when writing your own exception classes.

    • All exceptions must be subclasses of Throwable.
    • If you want to write an inspection exception class, you need to inherit the Exception class.
    • If you want to write a run-time exception class, you need to inherit the RuntimeException class.

You can define your own exception class as follows:

Class myexception extends Exception{ }

Let's look at a complete example:

1  Packagecom.czgo.exception;2 3 /**4 * Custom Exception classes (inherited runtime Exceptions)5  * @authorAlanlee6  * @version2016/11/267  */8  Public classMyExceptionextendsRuntimeException {9 Ten     Private Static Final LongSerialversionuid = 1L; One  A     /** - * Error code -      */ the     PrivateString ErrorCode; -  -     /** - * Whether the message is a key in the properties file +      */ -     Private BooleanPropertieskey =true; +  A     /** at * Constructs a basic exception. -      * -      * @parammessage - * Information Description -      */ -      Publicmyexception (String message) in     { -         Super(message); to     } +  -     /** the * Constructs a basic exception. *      * $      * @paramErrorCodePanax Notoginseng * Error code -      * @parammessage the * Information Description +      */ A      Publicmyexception (String errorCode, String message) the     { +          This(ErrorCode, message,true); -     } $  $     /** - * Constructs a basic exception. -      * the      * @paramErrorCode - * Error codeWuyi      * @parammessage the * Information Description -      */ Wu      Publicmyexception (String errorCode, String message, Throwable cause) -     { About          This(errorCode, message, cause,true); $     } -  -     /** - * Constructs a basic exception. A      * +      * @paramErrorCode the * Error code -      * @parammessage $ * Information Description the      * @paramPropertieskey the * Whether the message is a key in the properties file the      */ the      PublicMyException (string errorCode, String message,BooleanPropertieskey) -     { in         Super(message); the          This. Seterrorcode (ErrorCode); the          This. Setpropertieskey (Propertieskey); About     } the  the     /** the * Constructs a basic exception. +      * -      * @paramErrorCode the * Error codeBayi      * @parammessage the * Information Description the      */ -      PublicMyException (string errorCode, String message, Throwable cause,BooleanPropertieskey) -     { the         Super(message, cause); the          This. Seterrorcode (ErrorCode); the          This. Setpropertieskey (Propertieskey); the     } -  the     /** the * Constructs a basic exception. the      *94      * @parammessage the * Information Description the      * @paramcause the * Root Exception Class (can deposit any exception)98      */ About      Publicmyexception (String message, throwable cause) -     {101         Super(message, cause);102     }103     104      PublicString GetErrorCode () the     {106         returnErrorCode;107     }108 109      Public voidSeterrorcode (String errorCode) the     {111          This. ErrorCode =ErrorCode; the     }113  the      Public BooleanIspropertieskey () the     { the         returnPropertieskey;117     }118 119      Public voidSetpropertieskey (BooleanPropertieskey) -     {121          This. Propertieskey =Propertieskey;122     }123     124}

To throw exception information using a custom exception:

1  Packagecom.czgo.exception;2 3  Public classMyexceptiontest {4 5      Public Static voidMain (string[] args) {6         7String[] Sexs = {"Male", "female", "neutral"};8           for(inti = 0; i < sexs.length; i++){9              if("neutral". Equals (Sexs[i])) {Ten                  Throw NewMyException ("Your whole family is neutral!") "); One}Else{ A System.out.println (Sexs[i]); -              } -          }  the     } -}

Operation Result:

It's that simple, my words implement a lot of constructors that can throw the corresponding custom exceptions according to the actual business requirements.

Concluding remarks: Now engaged in software development more and more people, master countless, rookie also countless, the line of the market stirred more chaotic. So the first to enter this line of the brothers must have a sense of crisis. Companies want to open the salary is not high, but also can do a lot of things people, engage in development is very tired, but in the current environment, must constantly to improve themselves. To shuffle the time, may be eliminated in the person inside you, unless you go to do something else, or you have to bite the bullet for a few years to make a solid technology, the review of the knowledge of a lot of review, the knowledge of learning a lot of learning, the foundation of solid to see the underlying things, such as understanding Java Virtual Machine, Research on spring source code. Pay more attention to the development of cutting-edge technology, because the things you use now may one day most companies will not be able to meet the needs of the project, it is possible. Hope everyone can mix out their own piece of heaven and Earth, little Alan is still eating in the soil, so we all together forward, the world is the young people, do not be discouraged.

Custom Exceptions for Java exceptions

Related Article

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.