请提供一种方式,可以让Java抛出经过检查的异常而不需要try-catch或者声明在throws子句
注意:
①不能使用已过时方法(方法上标注@deprecated)
②使用Java编写而非JVM字节码
③禁止编译后修改class文件或者dex文件
④不需要适应所有的异常
⑤在未经过检查的异常中包含一个经过检查的异常算作未经过检查的异常
我来提供一种方法(使用Thrower.sneakyThrow(Throwable)抛出经过检查的异常):
class Thrower
{
private Throwable e;
private Throw() throws Throwable
{
throw e;
}
public static synchronized void sneakyThrow(Throwable e)
{
Throw.e=e;
try
{
Throw.class.newInstance();
}
catch(InstantiationException t)
{
throw new IllegalArgumentsException();
}
catch(IllegalAccessException t)
{
throw new IllegalArgumentsException();
}
finally
{
Throw.e=null;
}
}
}
注意:
①不能使用已过时方法(方法上标注@deprecated)
②使用Java编写而非JVM字节码
③禁止编译后修改class文件或者dex文件
④不需要适应所有的异常
⑤在未经过检查的异常中包含一个经过检查的异常算作未经过检查的异常
我来提供一种方法(使用Thrower.sneakyThrow(Throwable)抛出经过检查的异常):
class Thrower
{
private Throwable e;
private Throw() throws Throwable
{
throw e;
}
public static synchronized void sneakyThrow(Throwable e)
{
Throw.e=e;
try
{
Throw.class.newInstance();
}
catch(InstantiationException t)
{
throw new IllegalArgumentsException();
}
catch(IllegalAccessException t)
{
throw new IllegalArgumentsException();
}
finally
{
Throw.e=null;
}
}
}