当前正在处理一个项目,这是我无法获得的内容的过分简化的视图。
public class throwseg1
{
void show() throws Exception
{
try{
int k = 1/0;
}catch (ArithmeticException e){
throw e;
}
try {
throw new Exception("my.own.Exception");
}catch (Exception e){
throw e;
}
}
void show2() throws Exception // Why just Exception is necessary here, not ArithmeticException ?
{
show();
}
void show3() throws Exception // Why just Exception is necessary here, not ArithmeticException ?
{
show2();
}
public static void main(String s[]) // Why just Exception is necessary here, not ArithmeticException ?
{
try {
throwseg1 o1 = new throwseg1();
o1.show3();
}catch (ArithmeticException e){
System.out.println("Caught Arithmetic ");
}catch (Exception e){
System.out.println("Caught");
}
}
}
在Jakson中,有一个ObjectMapper从ObjectMapper源文件中抛出JsonException e它。
public String writeValueAsString(Object value)
throws JsonProcessingException
{
// alas, we have to pull the recycler directly here...
SegmentedStringWriter sw = new SegmentedStringWriter(_jsonFactory._getBufferRecycler());
try {
_configAndWriteValue(_jsonFactory.createGenerator(sw), value);
} catch (JsonProcessingException e) {
throw e;
} catch (IOException e) { // shouldn't really happen, but is declared as possibility so:
throw JsonMappingException.fromUnexpectedIOE(e);
}
return sw.getAndClear();
}
每当我使用此函数时,我都必须在方法声明中抛出JsonException,如下所示
public void publishAssetScope(String customerUuid, AssetScope assetScope)
throws JsonProcessingException {
//More code
publishMessage(customerUuid, jacksonObjectMapper.writeValueAsString(assetScope));
}
随后谁在调用publishAssetScope,我必须在方法签名中“抛出” JsonProcessingException。
其次,函数链中还有其他“抛出”“ new SomeException”异常,为什么我不必在其父调用函数的方法签名中将其作为抛出添加。
希望您能理解,我知道这是一个非常令人困惑的问题,我无法正确表达自己的意思。
谢谢
为什么我必须这样做?
当任何代码引发异常时,您有两个选择:
throws
在方法签名中使用关键字从调用代码中抛出try-catch
块在调用代码中捕获异常其次,函数链中还有其他异常“抛出”“ new SomeException”,为什么我不必在方法签名中将其添加为抛出
如果抛出的异常是Checked Exception,则必须抛出或捕获它,但是如果抛出的异常是Unchecked Exception,则可以跳过捕获或抛出它。
检查异常:
属于的子类型的例外Exception
(不包括的子类型RuntimeException
)被归类为已检查的例外。
未经检查的异常:
属于子类型Error
且RuntimeException
属于未检查的异常的异常。
有关已检查和未检查的异常的详细信息,请参见Java中已检查和未检查的异常。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句