Java Learning 12: Exception

concept

The situation is not normal procedure at run time.

Abnormal Origin

The problem is a real concrete things in life, can also be described in the form of java class and packaged as an object, in fact, the situation is not normal for java objects reflect the description.
There are two problems for division: severe, java classes described by Error, generally do not write specific code to process it; is not serious, described by Exception class, may be used for targeted treatment process.
Throwable
| -error
| -Exception

Exception Handling

the try
{
to be detected codes;
}
the catch (Exception class variables)
{
code that handles; (treatment)
}
the finally
{
statement will be executed;
}

/*
    div 0!
    / by zero
    java.lang.ArithmeticException: / by zero
    java.lang.ArithmeticException: / by zero
    at Function.div(Demo.java:178)
    at Demo.main(Demo.java:187)
    over
*/
class Function
{
    double div(int a, int b)
    {
        return a / b;//(1) new AritchmeticException()
    }
}
class Demo
{
    public static void main(String[] args)
    {
        Function f = new Function();
        try {
            double x = f.div(1, 0);//(2) (1)传过来的new AritchmeticException()
            System.out.println("x = " + x);
        }
        catch(Exception e)//(3) Exception e = new AritchmeticException();
        {
            System.out.println("div 0!");
            System.out.println(e.getMessage());
            System.out.println(e.toString());// 异常名称:异常信息
            e.printStackTrace();// 异常名称,异常信息,异常出现的位置  其实JVM默认的异常处理机制,就是在调用printStackTrace方法,打印异常的堆栈的跟踪信息。
        }
        System.out.println("over");
    }
}

Abnormal objects captured were common method of operation

String getMessage () Returns the detail message string of this throwable
String toString () Returns the short form of this throwable
void printStackTrace () this throwable and its backtrace to the standard error stream

throws

On the function declaration function may be a problem by the keyword throws. Easy to improve safety, allow the caller to process (capture or throw), does not handle compilation fails.

class Function
{
    double div(int a, int b) throws Exception
    {
        return a / b;
    }
}
class Demo
{
    public static void main(String[] args) //throws Exception
    {
        Function f = new Function();
        try {//不捕获编译会报错(或者在主函数后面抛出异常)  Error:(187, 29) java: 未报告的异常错误java.lang.Exception; 必须对其进行捕获或声明以便抛出
            double x = f.div(1, 0);
            System.out.println("x = " + x);
        }
        catch(Exception e)
        {
            System.out.println(e.toString());

        }
        System.out.println("over");
    }
}

For multi-processing abnormalities

  1. When unusual statement, statement of recommendations for the more specific exceptions, such treatment can be more specific.
  2. The other statement a few exceptions, there are several on the corresponding catch block. If an exception occurs in the inheritance plurality of catch, the catch block parent abnormality on the bottom.
  3. During processing catch, catch sure to define the specific approach, not simply define a e.printStackTrace (), and do not write a simple output statement.
class Function
{
    double div(int a, int b) throws ArithmeticException, ArrayIndexOutOfBoundsException
    {
        int[] x = new int[a];
        System.out.println(x[4]);
        return a / b;
    }
}
class Demo
{
    public static void main(String[] args) //throws Exception  抛给虚拟机
    {
        Function f = new Function();
        try {
            double x = f.div(5, 0);
            System.out.println("x = " + x);
        }
        catch(ArithmeticException e)//java.lang.ArithmeticException: / by zero
        {
            System.out.println(e.toString());
            System.out.println("div 0!");
        }
        catch(ArrayIndexOutOfBoundsException e)//java.lang.ArrayIndexOutOfBoundsException: 4
        {
            System.out.println(e.toString());
            System.out.println("数组越界!");
        }
        System.out.println("over");
    }
}

Custom exception

Because there will be issues specific to the project, these problems have not been described and packaged java objects, so these problems can be specific to the unique problems abnormal package customized package in accordance with java on issues of ideology.
Requirements: This program, for the divisor is a negative number, also considered to be wrong, is not carried out operations, you need only describe this issue custom.

/*
    FuShuException
    div FuShu!
    over
*/
class FuShuException extends Exception//自定义异常
{}
class Function
{
    double div(int a, int b) throws ArithmeticException, FuShuException
    {
        if(b < 0)
            throw new FuShuException();
        return a / b;
    }
}
class Demo
{
    public static void main(String[] args)
    {
        try
        {
            double result = new Function().div(1, -1);
            System.out.println("result = " + result);
        }
        catch(ArithmeticException e)
        {
            System.out.println(e.toString());
            System.out.println("div 0!");
        }
        catch(FuShuException e)
        {
            System.out.println(e.toString());
            System.out.println("div FuShu!");
        }
        System.out.println("over");
    }
}

Print result of the program, only unusual name, but no unusual information, because exceptions are not defined customized information. How to define anomalies?
Because the parent has the abnormal operation information are completed, so subclasses as long as at the time of construction, the exception information is passed to the parent class by super statement, then you can get an exception customized information directly through the getMessage method (toString call getMessage method). The following program specific information also contains transfer.

/*
    FuShuException: / by fushu
    div FuShu!
    illegal negative value is : -1
    over
 */
class FuShuException extends Exception//自定义异常
{
      private int value;
      FuShuException(String msg, int value)
      {
           super(msg);
           this.value = value;
      }
      int getValue()
      {
          return value;
      }
//    private String msg;
//    FuShuException(String msg)
//    {
//        this.msg = msg;
//    }
//    public String getMessage()
//    {
//        return msg;
//    }
}
class Function
{
    double div(int a, int b) throws ArithmeticException, FuShuException
    {
        if(b < 0)
            throw new FuShuException("/ by fushu", b);
        return a / b;
    }
}
class Demo
{
    public static void main(String[] args)
    {
        try
        {
            double result = new Function().div(1, -1);
            System.out.println("result = " + result);
        }
        catch(ArithmeticException e)
        {
            System.out.println(e.toString());
            System.out.println("div 0!");
        }
        catch(FuShuException e)
        {
            System.out.println(e.toString());
            System.out.println("div FuShu!");
            System.out.println("illegal negative value is : " + e.getValue());
        }
        System.out.println("over");
    }
}

Note: Custom Exception class must be inherited, the cause of inherited Exception:
Abnormal system has a feature, and because the exception class exception objects are thrown, they have disposable nature, this may throw Throwable of the unique characteristics of this system only this system of classes and objects can be throws and throw operation.

Throws and throw the difference

throws in the function, throw in the function.
behind with throws exception class, with a plurality of separated by commas. with the exception object is behind the throw.

RuntimeException

Exception has a special subclass of a RuntimeException abnormality (abnormal operation).
If the exception is thrown within a function, you can not declare a function, as compiled by (other abnormal compiler does not pass);
class Function
{
    double div(int a, int b)
    {
        if(b == 0)
            //throw new Exception("div zero!"); 就会报错"未报告的异常错误java.lang.Exception; 必须对其进行捕获或声明以便抛出"
            throw new ArithmeticException("div zero!");
        return a / b;
    }
}
class Demo
{
    public static void main(String[] args)
    {
        Function f = new Function();
        f.div(1, 0);
        System.out.println("over!");
    }
}

: If you declare the exception in the function, the caller can not be treated the same by the compiler.

class Function
{
    double div(int a, int b) throws ArithmeticException//如果是throws Exception,则会报错“未报告的异常错误java.lang.Exception; 必须对其进行捕获或声明以便抛出”
    {
        return a / b;
    }
}
class Demo
{
    public static void main(String[] args)
    {
        Function f = new Function();
        f.div(1, 0);
        System.out.println("over!");
    }
}

The reason is not used in the function declaration, because the caller does not need to let the process when the exception occurs, you want the program to stop ( my understanding is that this exception is too severe, has been unable to deal with ), due to conditions not continue operation at runtime after, I want to stop the program, the code amendment.

Therefore, a custom exception if the exception occurs, can no longer continue the operation, let custom exceptions inherited RuntimeException.

//Exception in thread "main" FuShuException: div Fushu!
class FuShuException extends RuntimeException
{
    FuShuException(String msg)
    {
        super(msg);
    }
}
class Function
{
    double div(int a, int b)//throws FuShuException
    {
        if(b < 0)
            //FuShuException继承了RuntimeException,所以不用声明异常,主函数不需要处理
            throw new FuShuException("div Fushu!");
        return a / b;
    }
}
class Demo
{
    public static void main(String[] args)
    {
        new Function().div(1, -2);
    }
}

Abnormal divided into two

  1. Compile-time abnormality is detected;
  2. Not detected abnormality (abnormality, RuntimeException and its subclasses runtime) Compiled

Exercise

class BlueScreenException extends Exception
{
    BlueScreenException(String msg)
    {
        super(msg);
    }
}
class SmokeException extends Exception
{
    SmokeException(String msg)
    {
        super(msg);
    }
}
class NoPlanException extends Exception
{
    NoPlanException(String msg)
    {
            super(msg);
    }
}
class Computer
{
    private int status = 2;
    public void run() throws BlueScreenException, SmokeException
    {
        if(status == 2)
            throw new BlueScreenException("电脑蓝屏!");
        else if(status == 3)
            throw new SmokeException("电脑冒烟!");
        System.out.println("电脑运行!");
    }
    public void reset()
    {
        System.out.println("电脑重启!");
    }
}
class Teacher
{
    public void test()
    {
        System.out.println("练习!");
    }
    public void prelect() throws NoPlanException
    {
        Computer comp =  new Computer();
        try {
            comp.run();
        }
        catch(BlueScreenException e)
        {
            System.out.println(e.toString());
            comp.reset();
        }
        catch(SmokeException e)
        {
            test();
            throw new NoPlanException("课程无法继续," + e.getMessage());
        }
        System.out.println("讲课!");
    }
}
class Demo
{
    public static void main(String[] args)
    {
        Teacher t = new Teacher();
        try {
            t.prelect();
        }
        catch (NoPlanException e)
        {
            System.out.println(e.toString());
            System.out.println("更换电脑");
        }
    }
}

finally block

Execution code defines a certain, usually for closing resources. (Closing operation of the database in the database on the inside)

Three formats

    //1
    try
    {
    }
    catch()
    {

    //2
    try
    {
    }
    catch()
    {
    }
    finally
    {
    }

    //3
    try
    {
    }
    finally
    {
    }

Note: catch is used to treat abnormal, if not catch on behalf of not being processed, if the exception is an exception, must be declared during testing, see the following procedures.

class Demo
{
    public void method()
    {
        //1.编译不能通过 解决方法:(1)声明异常throws Exception;(2)捕获异常
        throw new Exception();

        //2.编译能通过,捕获异常
        try
        {
            throw new Exception();
        }
        catch (Exception e)
        {

        }

        //3.编译不能通过,异常未被声明或捕获
        try
        {
            throw new Exception();
        }
        catch (Exception e)
        {
            throw e;
        }

        //4.编译能通过,捕获异常
        try
        {
            throw new Exception();
        }
        catch (Exception e)
        {
            try
            {
                throw e;
            }
            catch(Exception e2)
            {

            }
        }

        //5.编译不能通过,异常未被声明或捕获
        try
        {
            throw new Exception();
        }
        finally
        {
            //关闭资源
        }
    }
}

Abnormality reflected in the child-parent class overrides

  1. When cover subclass parent, if the parent class throws an exception, then the method of covering the subclass, the only exception is thrown, or a subclass of the class of the parent;
  2. If a plurality of parent class method throws exception, when subclasses override this method, only exception is thrown parent subset;
  3. If the parent class or interface methods are no exception is thrown, then the subclass in the overlay method, nor can throw an exception if the subclass method exception occurs, we must try to be treated, must not be sacrificed.

Examples of anomalies

class InvalidValueException extends RuntimeException
{
    InvalidValueException(String msg)
    {
        super(msg);
    }
}
interface Shape//接口类
{
    public abstract double getArea();
}
class Rec implements Shape//长方形
{
    private double len, width;
    Rec(double len, double width)
    {
        this.len = len;
        this.width = width;
    }
    public double getArea()
    {
        if(len <= 0 || width <= 0)
            throw new InvalidValueException("输入非法值!");
        return len * width;
    }
}
class Circle implements Shape
{
    double r;
    private static final double PI = 3.14;//因为PI是共享数据,所以加static
    Circle(double r)
    {
        this.r = r;
    }
    public double getArea()
    {
        if(r <= 0)
            throw new InvalidValueException("出现非法值");
        return r * r * PI;
    }
}
class Demo
{
    public static void main(String[] args)
    {
        Rec rec = new Rec(10, 2);
        System.out.println(rec.getArea());
        Circle circle = new Circle(-11);
        System.out.println(circle.getArea());
    }
}

to sum up

Exception is a description of the problem, the problem is encapsulated object.

Abnormal system:
Throwable
| -error
| -Exception
abnormal system features: Abnormal system for all classes and objects are created with a disposable nature, that can be operated throw and the throws keyword, only the abnormal system has this feature,

throw and throws Usage:
throw is defined in function throws an exception for the object;
throws defined on the function that throws exception class that is thrown plurality, separated by commas.

When the function contents throw thrown objects, try not be treated, must be declared on the function, otherwise fail to compile.
Note: RuntimeException except, that is, within a function If you throw RuntimeException exceptions, you can not declare the function. If the abnormal function declaration, the caller needs to be treated, treatment may be throws / try.

There are two exception:
Compiled by the abnormality detection, the abnormality if no treatment is not throws nor try, compilation fails, the exception is identified, the representative can be processed;
abnormality (not compile-time detection) run, not at compile time need to be addressed, the compiler does not check, when the exception occurs, treatment is not recommended, so that the program stops, the code needs to be corrected.

Exception handling statements
the try
{
code needs to be detected;
}
the catch ()
{
code that handles the exception;
}
the finally
{
code that will be executed;
}
Note:
(. 1) the finally defined normally closed source code, because the resources must be released ;
(2) finally only one case does not perform, when catch wrote when (0) System.exit exit system, jvm end, then finally inside the statement is not executed.

Custom class anomaly

According to the java object-oriented thinking, the problem occurred in the program specific to encapsulate, or a defined class inheritance Exception RuntimeException.
(1) In order for a custom class that includes a disposable property;
(2) make such an abnormal operation includes common method.

When information is to define the custom exception can be used have been defined parent class function, abnormality information is transmitted to the constructor of the superclass.

class MyException extends Exception
{
    MyException(String msg)
    {
        super(msg);
    }
}

Abnormal benefits
(1) to issue the package;
(2) normal flow of the code and phase separation problems handling code, easy to read.

Abnormality principles
(1) treatment: try or throws;
(2) function call to the thrown exception is thrown a few, a few to process, corresponding to a plurality of try the catch;
(. 3) a plurality of the catch, catch into the bottom of the parent class;
the (. 4) catch, to define a targeted approach, simply do not define printStackTrace output statement, nor else write;
(5) when the caught exception, not the present processing function you can continue to throw in the catch;

try
{
    cicle.getArea();
}
catch(InvalidValueException e)
{
    throw e;
}

(6) If not this exception process, but does not belong to the function abnormality occurs after abnormality can be converted again thrown and functionally related abnormalities; or exception handling may be, when it is desired to produce and the abnormality related to this function provide problem out, let the caller know and processing can also be converted to capture new exception after exception handling;

//1
try
{
    cicle.getArea();
}
catch(InvalidValueException e)
{
    throw new BException();
}
//2
try
{
    cicle.getArea();
}
catch(InvalidValueException e)
{
    //对e进行处理,之后抛出新的异常
    throw new BException();
}

Abnormality reflected in the child-parent class overrides

Published 146 original articles · won praise 244 · Views 1.01 million +

Guess you like

Origin blog.csdn.net/GSH_Hello_World/article/details/78397290