java_内部类_异常

内部类

这里写图片描述

异常

这里写图片描述

异常
---------------
    Exception

    java.lang.Object
    Throwable:可抛出的.
        |----<|---- Error           //错误
        |----<|---- Exception       //异常 try{}catch(Exception e){}finally{}

    throw       //抛出异常的语句
    throws      //声明抛出异常时使用的关键字

    try{
        ...
    }
    catch(Exception e){
        ....
    }
    finally{
        ...
    }
    finally是无论如何要执行的代码,可以在
    里面有返回语句,如果finally中返回语句,

    try{
        ...
    }
    catch(MyException1 e){
        ...
    }
    catch(MyException1 e){
        ...
    }

    1.定义AgeTooSmallException
    2.定义AgeInvalidException,AgeTooBigException和AgeTooSmallException继承该异常
    3.处理异常
        AgeTooSmallException
        AgeTooBigException
        AgeInvalidException
    CheckedException            //待检异常,非运行时异常,必须声明抛出语句。
    RuntimeException(空几个经典的RunTimeException如下:1.java.lang.NullPointerException;
2.java.lang.ArithmaticException;
3.java.lang.ArrayIndexoutofBoundsException)         //运行时异常,不需要在方法上声明抛出语句,也不需要必须使用trycatch语句处理。

方法覆盖时,只能抛出相同异常或者是子类,范围可以缩小,不能放大。

这里写图片描述

这里写图片描述

/**
 1.定义异常
 class xxx extends Exception{...}
 2.使用异常
 throw new MyException();
 3.处理异常
 a.try-catch-finally
 b.继续抛出
 */

这里写图片描述

这里写图片描述

这里写图片描述

1、检查型异常(CheckedException):这类异常都是Exception的子类。异常的向上抛出机制进行处理,加入子类可能产生A异常,那么父类中也必须throwsA异常,可能导致的问题:代码效率低,耦合度过高。
2、非检查型异常(UncheckedException):这类异常都是RuntimeException的子类,不能通过clientcode来试图解决。
在Java的异常中,Error和RuntimeException是非检查型异常,其他的都是检查型异常。另外,所有方法都可以在不声明throws的情况下抛出RuntimeException及其子类。


Exception:在程序中必须使用try...catch...进行处理。
RuntimeException:可以不使用try...catch...进行处理,但是若有异常产生,则异常将由JVM进行处理。
显而易见,所有的非RuntimeException都需要我们来处理。 当然,对于RuntimeException我们最好也用try...catch...处理。否则一旦异常发生,会导致程序中断。

构造函数可以使用抛出异常声明

class ExceptionDemo5 {
    public static void main(String[] args)  {
    }
}

class Person{
    public int age ;
    public void setAge(int age) throws AgeInvalidException{
        if(age < 0 || age > 200){
            throw new AgeTooBigException();
        }
        this.age = age ;
    }
}

//子类
class Chinese extends Person{
    public void setAge(int age) throws AgeTooSmallException{
        if(age < 0 ){
            throw new AgeTooSmallException();
        }
        this.age = age ;
    }
}

class AgeInvalidException extends Exception{
}
class AgeTooBigException extends AgeInvalidException{
}
class AgeTooSmallException extends AgeInvalidException{
}

猜你喜欢

转载自blog.csdn.net/weixin_37243717/article/details/80796948