Java Exception Handling

Source: Internet
Author: User
Tags define exception finally block getmessage throwable try catch

First, brief

Exception: This is when the program is running in an unhealthy situation.

Exception Origin: 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 is a description of the abnormal situation after the object.

For the division of the problem:

    • A serious problem.
    • Not a serious problem.

For serious, Java is described by the error class. The error is typically not written before the targeted code is processed. (It's hopeless, why bother?) )

For non-critical, Java is described by the exception class. For exception, you can use a targeted processing method for processing.

Both error and exception have some common content. Such as: abnormal information, cause and so on.

Throwable    |--Error    |--Exception
second, the treatment of abnormal

Java provides a unique statement to handle.

try{    //需要被检测的代码;}catch(异常类 变量){    //处理异常的代码(处理方式)}finally{    //一定会执行的语句}

Knowing C + + knows that there is no finally block in exception handling in C + +, so why do you have this in Java?

Only because there is no destructor in the Java object, in C + +, even if an exception is thrown, it will eventually execute to the destructor. So Java uses the function of the destructor to be represented by finally, just like a destructor, and the block is bound to execute, whether or not it throws an exception.

So for object destruction, resource shutdown, and so on, something that was originally written in the destructor, in Java, we can write it to finally.

third, processing the caught exception object
class Demo{    int div(int a, int b) throws ArithmeticException    {        if(b < 0)            throw new ArithmeticException();  //手动通过throw关键字抛出一个自定义的异常对象                    return a / b;    }}public class ExceptionDemo {    public static void main(String[] args) {        Demo d = new Demo();        try         {            int ret = d.div(4, 0);            System.out.println(ret);        }        catch(ArithmeticException e)        {            System.out.println("除数为0错误");            System.out.println(e.getMessage());  //by zero            System.out.println(e.toString());    //异常名称: 异常值            e.printStackTrace();  //异常名称,异常信息,异常出现的位置                                  //jvm默认的异常处理机制,便是在调用printStackTrace方法.                                  //打印异常的堆栈跟踪信息.        }    }}
Iv. The difference between throw and throws
    • Throws is used on a function to indicate that the function may have an exception. Throws followed by the exception class, you can follow multiple, separated by commas.
    • Throw uses the information inside the function to throw an exception.
      The throw is followed by an exception object.
five, multiple exception handling

When declaring an exception, it is recommended to declare more specific exceptions so that processing can be more specific.

To throw multiple exceptions, the throws is followed by a comma to separate the exception names, and to have a catch block that handles the exceptions separately.

In the catch, be sure to define the specific processing, do not simply define a sentence e.printstacktrace (), and do not write only one output statement.

You can log these exceptions to generate an exception log document.

VI. Custom Exceptions

Because there are some unique problems in the project, which are not described and encapsulated by Java, the specific problems can be encapsulated in a custom exception by the idea that Java encapsulates the problem.

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

Either the internal try catch is processed, or the function is declared to be handled by the caller.

In general, there is an exception in the function that needs to be declared on the function.

How do I define exception information?
Because the operation of the exception information has been completed in the parent class, the subclass will pass the exception information through the Super statement to the parent class whenever it is constructed. The information can then be output via GetMessage ().

Custom exceptions must be custom class inheritance exception.

Reasons for inheriting exception:
The exception system has a feature because both the exception class and the exception object are thrown.
They all have the ability to be parabolic, which is a unique feature of the Throwable system.
Only classes and objects in this system can be manipulated by throw and throws.

Seven, RuntimeException

There are two types of exceptions:

    • The exception that was detected at compile time.
    • Exceptions that are not detected at compile time, run-time exceptions, RuntimeException, and their subclasses.

RuntimeException is a special subclass exception in exception, called a run-time exception.

If the exception is thrown within a function, the function can be passed without declaration and compilation.

If the exception is declared on a function, the caller can pass the compilation without processing.

It is not declared on a function because it does not need to be handled by the caller. When the exception occurs, expect the program to stop. Because there is no continuation operation at runtime, the code is expected to be corrected after the program is stopped.

When you customize an exception, the custom exception inherits RuntimeException If the exception occurs, causing the operation to continue.

class Demo {    int div(int a, int b)    {        if(b == 0)            throw new ArithmeticException();  //手动通过throw关键字抛出一个自定义的异常对象        if(b < 0)            throw new FuShuException("除数为负数", b);  //运行期异常,无需声明throws也可编译通过                return a / b;    }}public class ExceptionDemo {    public static void main(String[] args) {        Demo d = new Demo();        try {            int ret = d.div(4, -1);            System.out.println("ret=" + ret);        }catch(ArithmeticException e) {            System.out.println(e.getMessage());        }    }}

Java Exception Handling

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.