Java 使用 if 语句尝试 catch 块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34016851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Try catch block with an if statement
提问by Essej
So I got some problems implementing a try catch block in my program. It's quite simple, all I want is to throw an exception whenever the user enters a 0 or less into my dialog window. Here is my code:
所以我在我的程序中实现 try catch 块时遇到了一些问题。这很简单,我只想在用户在我的对话框窗口中输入 0 或更少时抛出异常。这是我的代码:
try {
if (this.sides <= 0);
} catch (NegativeSidesException exception) {
System.out.println(exception + "You entered 0 or less");
}
The NegativeSidesException
is my own defined exception.
这NegativeSidesException
是我自己定义的异常。
When I make 0 the input the try catch block doesn't catch it and the compiler throws a normal exception and terminates the program.
当我将输入设为 0 时,try catch 块不会捕获它,并且编译器会抛出一个正常的异常并终止程序。
采纳答案by boskras
Change
if (this.sides <= 0);
改变
if (this.sides <= 0);
To
if (this.sides <= 0) throw new Exception ("some error message");
到
if (this.sides <= 0) throw new Exception ("some error message");
And every thing will work as you want
每件事都会如你所愿
回答by Kush
Create a new object for the exception and throw it explicitly.
为异常创建一个新对象并显式抛出它。
try{
if (this.sides <= 0)
throw new NegativeSidesException();
}
catch (NegativeSidesException exception)
{
System.out.println(exception + "You entered 0 or less");
}
回答by xxxvodnikxxx
You have so bad syntax :)
你的语法太糟糕了:)
1) if
statement as it is doesn't throw exception of it's own
1)if
语句本身不会抛出异常
Lets repeat :)
让我们重复一遍:)
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-Catch:
试着抓:
try{
//danger code
}catch(ExceptionClass e){
//work with exception 'e'
}
2) There are more ways how to make that :
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");
}
Or maybe better:
或者也许更好:
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");
}
Btw You can use java default Exception(that message is better to specify as constant in above of class):
顺便说一句,您可以使用 java 默认异常(该消息最好在类的上面指定为常量):
throw new Exception("You entered 0 or less);
//in catch block
System.out.println(e.getMessage());