Java Tour (10)-Overview of exceptions, Try-catch, exception declarations throws, multiple exception handling, custom exceptions, throw and throws differences

Source: Internet
Author: User
Tags define exception getmessage

Java Tour (10)-Overview of exceptions, Try-catch, exception declarations throws, multiple exception handling, custom exceptions, throw and throws differences

Unknowingly, the Java tour this series has been updated to the tenth, feeling like a dream, time flies quickly, in an instant one months so passed, we don't say, continue our Java Tour

I. Overview of exceptions

Anomaly is a relatively important part of the program, we first look at the abnormal system, we give a small example, define a division method

//public class class name Public  class Hellojjava {    //public static no return value the Main method array     Public Static void Main(string[] str) {Demo d =NewDemo (); System.out.println (D.Div (6,2)); }}class Demo {/** * defines a division * * @param A * @param b * @return  */    intDivintAintb) {returnA/b; }}

This procedure is very well understood, that is, in addition, 6 and 2 go in, the result must be 3 ah, but, I now pass a 4 and 0, the output of the results will be what?

OK, there's an anomaly.

    • Exception: The abnormal condition that occurs when the program is running

The origin of the exception

    • The problem is also a specific thing in real life, can also be described in the form of Java classes, and encapsulated into objects, in fact, Java to describe the abnormal situation after the object of the embodiment

    • The division of the problem, divided into two, one is a serious problem, a non-serious problem, for serious problems Java through the Error class description, non-serious, with the exception class to describe

    • For error, generally do not write specific code to describe

    • For exception can be handled by positive-to-sexual processing

Whether error or exception, there are some common content, such as: abnormal information, cause and so on

    • Throwable
      • Error
      • Exception

Error is a lot of errors, you are basically a lot can be based on the name to catch what is wrong

But we're not talking about error today, we're looking at anomalies.

Two. Try-catch

Try-catch is throwing an exception, that is, handling the exception

    try {            //需要被检测的代码        catch (Exception e) {            // 处理异常的代码(处理方式)        }

Now that we know how to handle it, we can deal with the exception above.

//public class class name Public  class Hellojjava {    //public static no return value the Main method array     Public Static void Main(string[] str) {Demo d =NewDemo ();Try{System.out.println (D.Div (4,2)); }Catch(Exception e) {System.out.println ("Exception"); }}}class Demo {/** * defines a division * * @param A * @param b * @return  */    intDivintAintb) {returnA/b; }}

Common handling methods for incoming exception object input

    • GetMessage () error message
    • ToString () Converts exception information to string
    • Printstacktrace Trace information in print memory
Three. Exception declaration throws

We are not sure if this code is a problem, then we have to go to the logo, how to identify? Throws

/**     * 定义一个除法     *      * @param a     * @param b     * @return     */    int div(intintthrows Exception{        return a / b;    }

In the function of the throws keyword to declare that the function may be a problem, so we use the time will be prompted;

I won't let you use it if you don't deal with it, it improves security.

Three. Multiple exception handling

What is the way to handle multiple anomalies?

    • 1. When declaring an exception, it is recommended to declare a more specific exception so that the processing can be more specific
    • 2 The other side declares several exceptions, corresponding to several catch blocks, if the exception in multiple catch blocks has an inheritance relationship, the parent exception catch is placed at the bottom, do not define the extra catch block
    • 3. It is recommended that in the catch processing, the catch clock must define the specific processing method, do not simply define a sentence display format

Standard format

    try{        }catch{            // TODO Auto-generated catch block            e.printStackTrace();        }catch{        }

That is, multiple catch.

Four. Custom exceptions

We know that there are many kinds of anomalies, we can also customize the exception, that is, we define some rules, because there will be some unique exceptions in the project, and these problems are not encapsulated by the JAV as an exception, for these problems, we can follow the Java problem encapsulation of the idea, the unique problem of the custom exception encapsulation

How do I go about customizing exceptions?

requirements, in this program, for the out of the book is-1? is also considered to be wrong and cannot be performed, then a custom description of the problem is required.

When a throw throws an exception object inside a function, the corresponding processing action must be given

It is either declared on the function to let the caller handle

Throw keyword custom exception, in general, the function inside the exception, but there is no need to declare, found that the printing of the blame only the name of the exception, but no information, because the custom exception does not define the information

How to define exception information

//public class class name Public  class Hellojjava {    //public static no return value the Main method array     Public Static void Main(string[] str) {Demo d =NewDemo ();Try{D.dev (4, -1); }Catch(Fushuexception e) {//TODO auto-generated catch blockE.printstacktrace (); }    }}/** * Negative Number Exception * * @author LGL * */Class Fushuexception extends Exception {PrivateString msg; Public fushuexception(String msg) { This. msg = msg; }@Override     PublicStringGetMessage() {//TODO auto-generated method stub        returnMsg }}class Demo {intDevintAintbthrowsfushuexception {if(b <0) {//Manually throw custom exception objects through the Throw keyword            Throw NewFushuexception ("There was an exception with a negative number of divisor."); }returnA/b; }}

This piece of code is pretty fun.

But in fact, we do not know, this is actually the parent class has been completed, so as long as the child class construction, the construction of information passed to the parent class is OK, with super, then you can directly through the GetMessage () method to get the custom exception information

/** * 负数异常 *  * @author LGL * */class FushuException extends Exception {    private String msg;    public FushuException(String msg) {        super(msg);    }}
Five. The difference between throw and throws

Let's take a little episode where the difference between the two classes is abnormal

The difference between throw and throws

    • 1.Throws used on function, throw is used within function
    • 2.Throws followed by the exception class, you can follow multiple, with a comma difference, throw followed by the exception object

OK, we have this space first here, the exception of the content is still a lot of, no accident we next or the exception, we are interested in the words, can add group: 555974449

Java Tour (10)-Overview of exceptions, Try-catch, exception declarations throws, multiple exception handling, custom exceptions, throw and throws differences

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.