Java-based custom exceptions

Source: Internet
Author: User

Java-based custom exceptions

Oh, Mom, another exception! As the saying goes: "code abused me thousands of times, and I am waiting for code to be like my first love ".

Alan has been busy with his work recently and has not been writing anything for a long time to deepen his understanding. Today I will talk to you about Java exceptions. I am too lazy to go to BB for a Java exception system or something. I am familiar with Java development, but I may not understand it deeply. You can read more information by yourself, let me briefly talk about it.

What is an exception?

I don't know how everyone understands it. My understanding is simple. It is abnormal. For example, I am a man, but I have something unique to a woman, in my opinion, this Nima must be an exception and cannot be tolerated. Taking the above abnormal picture as an example, you should have a younger brother, but you have no younger brother. This is abnormal, so the Java girl will tell you, you should have a younger brother to do things, or you don't have to do things if you don't have a younger brother. If you don't have a younger brother or a younger brother, you can't do things, right?

It is often said that our ancestor is ape, and the ancestor of Exception is the Throwable class. Besides the Exception class, Throwable also has a subclass Error. If you encounter an Error, you can drop your computer and call... joke with everyone. This is not something that our program can handle. It is out of the scope of program processing. Exception can be divided into silly ones, so I won't be BB, and then BB will be B here.

Let's just list several exceptions:

RuntimeException: you cannot run fast enough, probably because you are too fat. Turn off your computer and go out for exercise.

NullPointerException: You have no dogs. Please first look for a dog, such as a bretany, and then try again.

IndexOutOfBoundsException: Place your index finger in a place that cannot be received, place it again, and try again.

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

NotSerializableException: you are trying to change a movie to a TV series.

What the hell is this Nima? I did not understand it. Fortunately, the object I want to understand today is not the above things. It's not good to make a mistake. Just look at it, but don't mess up. What men know, wow .. .. ....

 

Custom exception

What we need to understand today is what is a custom exception, why do we need to use a custom exception, what are the advantages of using a custom exception, and what are the disadvantages?

If you want to use a custom exception, you will get along with your girlfriend. First, you need to know why you want to be with your girlfriend. What are the advantages and disadvantages of your girlfriend, let's talk to your girlfriend about marriage. If you have been married for a lifetime, let's talk about these issues first. Finally, let's look at how to use custom exceptions. The implementation and use of custom exceptions are very simple, the key is to understand why content.

 

What are the advantages of using custom exceptions?

1. during our work, the project is developed by module or function. Basically, you will not develop a whole project by yourself. Using custom exception classes, we will unify the display of external exceptions.

2. sometimes, when we encounter some verification or problems, we need to directly end the current request, then we can end the process by throwing a custom exception, if SpringMVC is used in your project, the controller is enhanced, you can use the @ ControllerAdvice annotation to write a controller enhancement class to intercept custom exceptions and send response information to the front-end. (For more information about springMVC controller enhancements, please share with us ).

3. custom exceptions can be thrown when some special business logic is in our project, such as "neutral ". equals (sex), when the gender is equal to the neutral, we will throw an exception, and Java will not have this exception. Some errors in the system conform to the Java syntax, but do not conform to the business logic of our project.

4. When a custom exception inheritance exception is used to throw the exception information after processing, the underlying exception information can be hidden, Which is safer and more intuitive. Custom exceptions can throw the information we want to throw. The information can be used to identify the location where an exception occurs. Based on the Exception name, we can know where an exception exists, modify the program according to the exception prompt. For example, if a null pointer exception is NullPointException, we can throw the message "xxx is null" to locate the exception location without outputting stack information.

 

After talking about the benefits of using a custom exception, let's take a look at the issues with the custom exception:

Undoubtedly, we cannot expect the JVM (Java Virtual Machine) to automatically throw a custom exception, nor can we expect the JVM to automatically handle a custom exception. You must use the Exception Handling Mechanism in your code to discover, throw, and handle exceptions. In this way, the development cost and workload are increased accordingly. Therefore, if the project is unnecessary, it is not necessary to use custom exceptions, so you must be able to weigh them by yourself.

 

Finally, let's see how to use the custom exception:

You can customize exceptions in Java. Note the following when writing your own exception classes.

  • All exceptions must be a subclass of Throwable.
  • If you want to write a checking Exception class, you must inherit the Exception class.
  • If you want to write a runtime exception class, you must inherit the RuntimeException class.

You can define your own exception classes as follows:

Class MyException extends Exception {}

 

Let's look at a complete example:

1 package com. czgo. exception; 2 3/** 4 * custom exception class (inheriting runtime exceptions) 5 * @ author AlanLee 6 * @ version 2016/11/26 7 */8 public class MyException extends RuntimeException {9 10 private static final long serialVersionUID = 1L; 11 12/** 13 * Error Code 14 */15 private String errorCode; 16 17/** 18 * indicates whether the message is the Key 19 */20 private boolean propertiesKey = true in the attribute file; 21 22/** 23 * Indicates a basic exception. 24*25 * @ param message 26 * message description 27 */28 public MyException (String message) 29 {30 super (message ); 31} 32 33/** 34 * construct a basic exception. 35*36 * @ param errorCode 37 * error code 38 * @ param message 39 * Information Description 40 */41 public MyException (String errorCode, String message) 42 {43 this (errorCode, message, true); 44} 45 46/** 47 * construct a basic exception. 48*49 * @ param errorCode 50 * error code 51 * @ param message 52 * Information Description 53 */54 public MyException (String errorCode, String message, Throwable cause) 55 {56 this (errorCode, message, cause, true); 57} 58 59/** 60 * construct a basic exception. 61*62 * @ param errorCode 63 * Error Code 64 * @ param message 65 * Information Description 66 * @ param propertiesKey 67 * Whether the message is Key 68 */69 public MyException in the property File (String errorCode, string message, boolean propertiesKey) 70 {71 super (message); 72 this. setErrorCode (errorCode); 73 this. setPropertiesKey (propertiesKey); 74} 75 76/** 77 * construct a basic exception. 78*79 * @ param errorCode 80 * error code 81 * @ param message 82 * Information Description 83 */84 public MyException (String errorCode, String message, Throwable cause, boolean propertiesKey) 85 {86 super (message, cause); 87 this. setErrorCode (errorCode); 88 this. setPropertiesKey (propertiesKey); 89} 90 91/** 92 * construct a basic exception. 93*94 * @ param message 95 * description 96 * @ param cause 97 * root exception class (any exception can be saved) 98 */99 public MyException (String message, Throwable cause) 100 {101 super (message, cause); 102} 103 104 public String getErrorCode () 105 {106 return errorCode; 107} 108 109 public void setErrorCode (String errorCode) 110 {111 this. errorCode = errorCode; 112} 113 114 public boolean isPropertiesKey () 115 {116 return propertiesKey; 117} 118 119 public void setPropertiesKey (boolean propertiesKey) 120 {121 this. propertiesKey = propertiesKey; 122} 123 124}

Use a custom exception to throw exception information:

1 package com. czgo. exception; 2 3 public class MyExceptionTest {4 5 public static void main (String [] args) {6 7 String [] sexs = {"male", "female ", "neutral"}; 8 for (int I = 0; I <sexs. length; I ++) {9 if ("neutral ". equals (sexs [I]) {10 throw new MyException ("your family is neutral! "); 11} else {12 System. out. println (sexs [I]); 13} 14} 15} 16}

Running result:

This is simple. In my case, many constructor functions are implemented, which can throw corresponding custom exceptions based on actual business needs.

 

Conclusion: there are now more and more people engaged in software development, and there are countless experts and cainiao players. This is a mess in the market. Therefore, the first buddies in this line must have a sense of crisis. The company is tired of developing people who want to do things with low salaries, but they must constantly improve themselves in the current environment. When shuffling, there may be you in the people who may be eliminated. Unless you do something else, you will work hard on your head for several years to make the technology solid, and the knowledge to be reviewed will be reviewed, you can learn more about this learning. When you have a solid foundation, you can look at the underlying things, such as understanding the Java Virtual Machine and studying the Spring source code. Pay more attention to the development of cutting-edge technologies, because most of the companies you are using may not need to use one day or cannot meet the needs of projects. This is all possible. I hope everyone will be able to share their own world. Alan is still in the field, so everyone is moving forward together. After all, this world belongs to young people. Don't be discouraged.

 

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.