Let's talk about Java exceptions.

Source: Internet
Author: User
Tags terminates throwable

What is an exception

When the program runs, unexpected events occur that prevent the program from executing as expected by the programmer, which is an exception. When the exception occurs, is any program to fend for itself, immediately quit terminating, or output errors to the user? or in C language style: Use function return value as execution state?

Java provides a better solution: exception handling mechanisms.

Exception handling mechanism can let the program in the event of an exception, in accordance with the code's pre-set exception handling logic, targeted handling of exceptions, so that the program to the maximum possible return to normal and continue to execute, and keep the code clear.
Exceptions in Java can be raised when a statement executes in a function, or it can be thrown manually by a throw statement, as long as an exception is generated in a Java program and a corresponding type of exception object is used to encapsulate the exception, and the JRE tries to find the exception handler to handle the exception.

The Throwable class is the top-level parent of the Java exception type, an object that is only an instance of the Throwable class (direct or indirect), which is an exception object that can be identified by the exception handling mechanism. There are some common exception classes built into the JDK, and we can also customize exceptions.

Classification and class structure diagram of Java exceptions

Some common exceptions are built into the Java Standard library, which take throwable as the top-level parent class.

Throwable also derives the error class and the exception class.

Error: An instance of the error class and his subclass represents the JVM's own error. Errors cannot be handled by programmers through code, and error rarely occurs. Therefore, programmers should focus on the various exception classes under the branch of the parent class exception.

Exceptions: Exception and his subclasses represent a variety of unexpected events that are sent when the program is run. Can be used by the Java exception handling mechanism, which is the core of exception handling.

In general, we divide the exception class into 2 classes according to Javac's processing requirements for exceptions.

non-check exceptions (unckecked exception): Error and RuntimeException and their subclasses. Javac does not prompt and discover such exceptions at compile time, and does not require the program to handle these exceptions. So if we want to, we can write the code to handle (using try...catch...finally) Such an exception, or we can not handle. For these exceptions, we should fix the code instead of going through the exception handler. Most of the reason for this exception is that there is a problem with code writing. If, except for 0 error arithmeticexception, the wrong coercion type casts error classcastexception, the array index crosses the arrayindexoutofboundsexception, Empty object nullpointerexception are used, and so on.

Check for exceptions (checked exception): Other exceptions except error and runtimeexception. Javac forces programmers to prepare for such exceptions (using try...catch...finally or throws). The method either captures it with the Try-catch statement and processes it, or throws it with a throws clause declaration, or the compilation does not pass. Such exceptions are generally caused by the operating environment of the program. Because the program may be running in a variety of unknown environments, and the programmer cannot interfere with how the user uses the program he wrote, the programmer should be prepared for such an unusual moment. such as SqlException, ioexception,classnotfoundexception and so on.

It needs to be clear that the inspection and non-inspection is for javac, so it is well understood and differentiated.

Why do I want to customize exceptions

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.

How to customize exceptions

If you want to customize the exception class, you can extend the exception class so that such custom exceptions belong to the check exception (checked exception). If you want to customize non-check exceptions, extend from RuntimeException.

According to international practice, custom exceptions should always contain the following constructors:

    • An argument-free constructor

    • A constructor with a string argument and passed to the constructor of the parent class.

    • One with the string parameter and the Throwable argument, and all passed to the parent class constructor

    • A constructor with the Throwable parameter and passed to the constructor of the parent class.

The following is the complete source code for the IOException class, which can be used for reference.

/**
* MIT License
* Copyright (c) 2018 Haihua.liu
* Permission is hereby granted, free of charge, to all person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* In the software without restriction, including without limitation the rights
* To use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* Copies of the software, and to permit persons to whom the software are
* Furnished to does so, subject to the following conditions:
* The above copyright notice and this permission notice shall is included in all
* Copies or substantial portions of the software.
* The software is provided ' as is ', without WARRANTY of any KIND, EXPRESS OR
* implied, including but not LIMITED to the warranties of merchantability,
* FITNESS for A particular PURPOSE and noninfringement. In NO EVENT shall the
* AUTHORS or COPYRIGHT holders be liable for any CLAIM, damages or other
* Liability, WHETHER in a ACTION of contract, TORT OR OTHERWISE, arising from,
* Out of OR in CONNECTION with the software or the use or other dealings in the
* Software.
*/
Package cn.liuhaihua.web.exception;

/**
* @ClassName: Serviceexception
* @Description: Custom Service exception
* @author Liuhaihua
* @date July 5, 2018
*
*/
public class Serviceexception extends RuntimeException {

Private static final long serialversionuid = 1L;

/**
* Error code
*/
Private String ErrorCode;

/**
* Whether the message is a key in the properties file
*/
Private Boolean Propertieskey = true;

/**
* Constructs a basic exception.
*
* @param message
* Information Description
*/
Public serviceexception (String message)
{
Super (message);
}

/**
* Constructs a basic exception.
*
* @param errorCode
* Error code
* @param message
* Information Description
*/
Public Serviceexception (String errorCode, String message)
{
This (errorCode, message, true);
}

/**
* Constructs a basic exception.
*
* @param errorCode
* Error code
* @param message
* Information Description
*/
Public Serviceexception (String errorCode, String message, Throwable cause)
{
This (errorCode, message, cause, true);
}

/**
* Constructs a basic exception.
*
* @param errorCode
* Error code
* @param message
* Information Description
* @param propertieskey
* Whether the message is a key in the properties file
*/
Public Serviceexception (String errorCode, String message, Boolean Propertieskey)
{
Super (message);
This.seterrorcode (ErrorCode);
This.setpropertieskey (Propertieskey);
}

/**
* Constructs a basic exception.
*
* @param errorCode
* Error code
* @param message
* Information Description
*/
Public Serviceexception (String errorCode, String message, Throwable cause, Boolean propertieskey)
{
Super (message, cause);
This.seterrorcode (ErrorCode);
This.setpropertieskey (Propertieskey);
}

/**
* Constructs a basic exception.
*
* @param message
* Information Description
* @param cause
* Root Exception Class (can deposit any exception)
*/
Public serviceexception (String message, throwable cause)
{
Super (message, cause);
}

Public String GetErrorCode ()
{
return errorCode;
}

public void Seterrorcode (String errorCode)
{
This.errorcode = ErrorCode;
}

public boolean Ispropertieskey ()
{
return propertieskey;
}

public void Setpropertieskey (Boolean propertieskey)
{
This.propertieskey = Propertieskey;
}

}

Exception usage Precautions

When you use multiple catch statement blocks to catch an exception, you need to place the catch statement block of the parent class after the catch block of the child type to ensure that subsequent catch may be executed, otherwise the catch of the subtype will never arrive, and the Java compiler will report a compilation error.

If a return statement exists in a try statement block, the code in the finally statement block is executed first before it is returned.

If the System.exit (0) statement exists in a try statement block, then the code for the finally statement block is not executed for long because System.exit (0) terminates the currently running JVM. The program ends execution before the JVM terminates.


Let's talk about 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.