没有ServletException的Serlvet的init方法 [英] init method of a Serlvet without ServletException
问题描述
这是如何工作的。
mC的签名是mA签名的子签名(§8.4.2)。
其中 subsignature
被定义为
两个方法或构造函数M和N具有相同的签名,如果它们的
具有相同的名称,相同的类型参数(如果有的话)(§8.4.4),而
在适应正式参数类型N的类型
参数M,相同的形式参数类型。
方法m1的签名是签名的子签名a
方法m2如果有:
m2有与m1相同的签名,或
m1的签名与m2签名的擦除(§4.6)相同。
/ li>
所以一个 throws
子句可以忽略在小孩班。但是,给定 m2
覆盖 m1
如果m2有一个引用任何检查的异常类型的throws子句,那么
则m1必须有一个throws子句,或者发生编译时错误。
对于m2中throws子句中列出的每个被检查的异常类型,
同样的异常类或其超类型必须出现在
擦除(§4.6 )的m1的throws子句;否则,会出现编译时
错误。
例如
class Bar {
public void method()throws Exception {}
}
class Foo extends Bar {
@Override
public void method(){}
}
如果你执行
Bar bar = new Foo();
bar.method(); //你需要处理它,但它永远不会发生
Foo foo = new Foo();
foo.method(); //你不需要处理,它仍然不会发生
但是, / p>
class Bar {
public void method()throws SomeCheckedException {}
}
class Foo extends Bar {
@Override
public void method()throws SomeOtherUnrelatedCheckedException {}
}
将失败
Bar bar = new Foo();
bar.method(); // Bar说一些异常可能会发生,但实际的对象可能会抛出另一个异常,它不会被处理。
Though ServletException is a checked exception, I am able create a Servlet by extending HttpServlet and creating a init method with out throwing or catching the ServletException. The compiler didn't complain and the Servlet works as well.
How come this works.
One of the rules for overriding is that
The signature of mC is a subsignature (§8.4.2) of the signature of mA.
where subsignature
is defined as
Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (§8.4.4), and, after adapting the formal parameter types of N to the the type parameters of M, the same formal parameter types.
The signature of a method m1 is a subsignature of the signature of a method m2 if either:
m2 has the same signature as m1, or
the signature of m1 is the same as the erasure (§4.6) of the signature of m2.
So a throws
clause can be ignored in the child class. However, given m2
overrides m1
If m2 has a throws clause that mentions any checked exception types, then m1 must have a throws clause, or a compile-time error occurs.
For every checked exception type listed in the throws clause of m2, that same exception class or one of its supertypes must occur in the erasure (§4.6) of the throws clause of m1; otherwise, a compile-time error occurs.
Take the example
class Bar {
public void method() throws Exception {}
}
class Foo extends Bar {
@Override
public void method() {}
}
If you do
Bar bar = new Foo();
bar.method(); // you'll need to handle it, but it will never happen
Foo foo = new Foo();
foo.method(); // you don't need to handle, it still won't ever happen
But the inverse
class Bar {
public void method() throws SomeCheckedException{}
}
class Foo extends Bar {
@Override
public void method() throws SomeOtherUnrelatedCheckedException{}
}
would fail
Bar bar = new Foo();
bar.method(); // Bar says some exception can happen, but the actual object may throw another, it wouldn't be handled.
这篇关于没有ServletException的Serlvet的init方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!