实现方法中的异常处理 [英] exception handling in the implemented method

查看:120
本文介绍了实现方法中的异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码给出了一个检查错误到 throws Exception

The code below gives a checked error to throws Exception:

import java.io.IOException;

interface some {
    void ss99() throws IOException;
}

public class SQL2 implements some {
    @Override
    public void ss99 () throws Exception {}
// ...
}

而下面的一个可以编译:

while the one below compiles fine:

import java.io.IOException;

interface some {
    void ss99() throws IOException;
}

public class SQL2 implements some {
    @Override
    public void ss99 () throws NullPointerException {}
// ...
}

Java在做什么逻辑 - 任何想法?

On what logic is Java doing this-- any ideas?

TIA。

推荐答案

throws 关键字表示一个方法或构造函数可以抛出一个异常,虽然不需要。

The throws keyword indicates that a method or constructor can throw an exception, although it doesn't have to.

让我们从您的第二个代码片段开始

Let's start with your second snippet

interface some {
    void ss99() throws IOException;
}

public class SQL2 implements some {
    @Override
    public void ss99 () throws NullPointerException {}
}

考虑

some ref = getSome();
try {
    ref.ss99();
} catch (IOException e) {
    // handle
}

所有你必须使用的是你的界面一些。我们(编译器)不知道它正在引用的对象的实际实现。因此,我们必须确保处理任何 IOException ,可能会抛出

All you have to work with is with your interface some. We (the compiler) don't know the actual implementation of the object it is referencing. As such, we have to make sure to handle any IOException that may be thrown.

SQL2 ref = new SQL2();
ref.ss99();

您正在使用实际的实现。这个实现保证它不会抛出 IOException (不声明它)。因此,您不需要处理它。您也不需要处理 NullPointerException ,因为它是一个未经检查的异常。

you're working with the actual implementation. This implementation guarantees that it will never throw an IOException (by not declaring it). You therefore don't have to deal with it. You also don't have to deal with NullPointerException because it is an unchecked exception.

关于您的第一个代码片段,稍微更改

Regarding your first snippet, slightly changed

interface some {
    void ss99() throws IOException;
}

public class SQL2 implements some {
    @Override
    public void ss99 () throws Exception { throw new SQLException(); }
}

考虑

some ref = new SQL2();
try {
    ref.ss99();
} catch (IOException e) {
    // handle
}

所以尽管你正在处理在接口中声明的异常,但是你将会发出一个被检查的异常, SQLException ,逃避未处理。编译器不能允许这个。

So although you are handling the exception declared in the interface, you would be letting a checked exception, SQLException, escape unhandled. The compiler cannot allow this.

必须声明一个覆盖的方法来抛出与父类相同的异常或其子类之一。

An overriden method must be declared to throw the same exception (as the parent) or one of its subclasses.

这篇关于实现方法中的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆