try catch
=负数时如何使用x
抛出异常?
例如,我所拥有的只是:
try {
if(DaysNum > 0){
return DaysNum;
}
}
catch(...){
}
答案 0 :(得分:2)
您可以抛出创建自定义检查的异常并像这样抓住它。
class NegativeException extends Exception {}
try {
if(DaysNum > 0){
return DaysNum;
}
throw new NegativeException("number is negative");
} catch (NegativeException e) {e.printStackTrace();}
或者您可以像这样抛出RuntimeException
try {
if(DaysNum > 0){
return DaysNum;
}
throw new IllegalArgumentException("number is negative");
} catch (IllegalArgumentException e) {e.printStackTrace();}
在此处设置look以查找已检查与未检查的异常之间的区别
答案 1 :(得分:1)
尝试,catch不是直接触发异常,而是当你希望抛出一个并且想要以特定的方式处理它时。
因此,如果您只想抛出异常,那么您的方法将如下所示:
if(DaysNum > 0){
return DaysNum;
}
else {
throw new DaysNegativeException();
}
请注意,还需要先创建DaysNegativeException
。
答案 2 :(得分:0)
您不需要使用catch块来抛出异常。您可以使用throw
关键字抛出异常。
if(DaysNum > 0){
return DaysNum;
}else{
throw new MyCustomExpception("With some message");
}
即使你可以在catch块中做一些事情。
答案 3 :(得分:0)
您不需要尝试捕获锁来抛出异常。
您可以使用:
if (x<0) throw new RuntimeException("x is negative");
答案 4 :(得分:0)
try catch块不会抛出异常。这是由
完成的throw
关键字。要抛出异常,你可以说
throw new Exception();
当前方法将暂停并向调用方法提供异常,直到它到达结尾或直到它到达try catch块并以try {} catch(Exception e){}作为签名。在catch的块中,您可以执行一些日志记录或替代代码来处理异常。
答案 5 :(得分:0)
您可以在此处使用自定义例外
if(DaysNum>0){
return DaysNum;
}else{
throw new NegativeDaysException();
}
用户定义的异常应扩展Exception类,以使其检查异常,其中调用方法将处理该异常
public class NegativeDaysException() extends Exception{}