所以我在程序中实现try catch块时遇到了一些问题。这很简单,我想要的只是当用户在对话框窗口输入0或更少时抛出异常。这是我的代码:
try{
if (this.sides <= 0);
}
catch (NegativeSidesException exception)
{
System.out.println(exception + "You entered 0 or less");
}
}
NegativeSidesException是我自己定义的异常。
当我输入0时,try catch块没有捕获它,编译器抛出正常异常并终止程序
答案 0 :(得分:6)
更改
if (this.sides <= 0);
要
if (this.sides <= 0) throw new Exception ("some error message");
每件事都会按你的意愿运作
答案 1 :(得分:5)
为异常创建一个新对象并显式抛出它。
try{
if (this.sides <= 0)
throw new NegativeSidesException();
}
catch (NegativeSidesException exception)
{
System.out.println(exception + "You entered 0 or less");
}
答案 2 :(得分:1)
你的语法很糟糕:)
1)if
声明,因为它不会抛出它自己的
让我们再说一遍:)
如果强>
if(condition){
//commands while true
}
if(condition)
//if there is just 1 command, you dont need brackets
if(condition){
//cmd if true
}else{
//cmd for false
}
//theoretically (without brackets)
if(condition)
//true command;
else
//false command;
<强>尝试捕获强>
try{
//danger code
}catch(ExceptionClass e){
//work with exception 'e'
}
2)有更多方法可以做到这一点:
try{
if (this.sides <= 0){
throw new NegativeSidesException();
}else{
//make code which you want- entered value is above zero
//in fact, you dont need else there- once exception is thrown, it goes into catch automatically
}
}catch(NegativeSidesException e){
System.out.println(e + "You entered 0 or less");
}
或者更好:
try{
if (this.sides > 0){
//do what you want
}else{
throw new NegativeSidesException();
}
}catch(NegativeSidesException e){
System.out.println(e + "You entered 0 or less");
}
顺便说一下你可以使用java default Exception(该消息最好在类的上面指定为常量):
throw new Exception("You entered 0 or less);
//in catch block
System.out.println(e.getMessage());