7.1异常

7.1异常

异常对象均为派生于Throwable类的一个实例,Throwable类下分为Errow类和Exception类,其中Errow类以及其子类描述了Java运行时的系统错误和资源耗尽错误,Exception类又可以下分为两类,即RuntimeException和其他异常。
由程序错误导致的异常是属于RuntimeException类,包括:错误的类型转换、数组访问越界和访问null指针。
不派生与RuntimeException类的异常包括:试图在文件后面读取数据、打开不存在的文件等
将派生于Error类和RuntimeException类的所有异常称为非受查异常,不需要声明抛出。而受查异常需要在方法首部声明(throws)。一个方法需要声明所有可能抛出的受查异常,被对应的异常处理器接受。


{
public Image loadImage(String s) throws FileNotFoundException,EOFException
{...}
}
  • 1
  • 2
  • 3
  • 4
  • 5

子类方法中声明的受查异常不能比超类方法中声明的异常更通用。
对于一个存在的异常类,抛出的过程:
1.找到合适的异常类,在方法签名后声明
2.创建这个类的对象
3.将对象抛出

String readData(Scanner in) throws EOFException
{
...
while(...)
{
    if(!in.hasNext())
    {
        if(n<len)
            throw new EOFException;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

也可以创建自己的异常类,均派生于Exception类或其子类,定义的类包含两个构造器:一是默认构造器,二是带有详细描述信息的构造器,能打印出详细信息

class FileFormatException extends Exception
{
    public FileFormatException() {}
    public FileFormatException(String gripe)
    {
        super(gripe)//Throwable(String message)
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

捕获异常:try/catch语句
try
{
….
}
catch(Exception e)
{
handler for this type;
}

带资源的try语句
try(Resource res = …)
{
work with res
}
try块退出时,会自动调用res.close(),即关闭使用的资源

选自 :http://blog.csdn.net/zhou373986278/article/details/78123115

原文地址:https://www.cnblogs.com/zgj544/p/7712744.html