同一个 Java 类中的 Try-Catch-Throw
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2394773/
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-Throw in the same Java class
提问by Carlos
Is it possible to catch a method in the current class the try-catch block is running on? for example:
是否可以在当前类中捕获 try-catch 块正在运行的方法?例如:
public static void arrayOutOfBoundsException(){
System.out.println("Array out of bounds");
}
.....
public static void doingSomething(){
try
{
if(something[i] >= something_else);
}
catch (arrayOutOfBoundsException e)
{
System.out.println("Method Halted!, continuing doing the next thing");
}
}
If this is possiblehow will it be the correct way to call the catch method?
如果这是可能的,那么调用 catch 方法的正确方法是什么?
If this is not possible, could anyone point me in the right direction, of how to stop an exception from halting my program execution in Java withouthaving to create any new classes in the package, or fixing the code that produces ArrayOutOfBoundsException error.
如果这是不可能的,任何人都可以向我指出正确的方向,如何阻止异常停止我在 Java 中的程序执行,而不必在包中创建任何新类,或修复产生 ArrayOutOfBoundsException 错误的代码。
Thanks in Advance,
提前致谢,
A Java Rookie
一个 Java 菜鸟
回答by Adam Batkin
What you are wanting to do is handle an Exception.
您想要做的是处理Exception。
public static void doingSomething(){
try {
if (something[i] >= something_else) { ... }
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Method Halted!, continuing doing the next thing");
}
}
That's all you need. No extra classes, no extra methods.
这就是你所需要的。没有额外的类,没有额外的方法。
An Exception is a special type of class that can be "thrown" (you can throw it yourself by using the throwkeyword, or Java may throw one for you if, for example, you try to access an array index that does not exist or try to perform some operation on a null). A thrown exception will "unwrap" your call stack ("escaping" from each function call) until your program finally terminates. Unless you catchit, which is exactly what the syntax above does.
Exception 是一种可以“抛出”的特殊类型的类(您可以使用throw关键字自己抛出它,或者 Java 可能会为您抛出一个,例如,如果您尝试访问不存在的数组索引或尝试对 a null)执行一些操作。抛出的异常将“解包”您的调用堆栈(从每个函数调用中“转义”),直到您的程序最终终止。除非你catch,这正是上面的语法所做的。
So if you were writing a function a()that called a function b()that called a function c()and c()threw an exception, but the exception was not caught in b()or c(), you could still catch it in a():
因此,如果您正在编写一个函数a(),该函数b()调用了一个函数,该函数调用了一个函数c()并c()抛出了一个异常,但该异常没有在b()or 中捕获c(),您仍然可以在 中捕获它a():
void a() {
try {
b();
catch (SomeExceptionClass e) {
// Handle
}
}
That said, if it is possible to prevent an exception from being thrown in the first place, that is often a better idea. In your particular case, this would be possible since all arrays in Java know their own length:
也就是说,如果可以首先防止抛出异常,那通常是一个更好的主意。在您的特定情况下,这是可能的,因为 Java 中的所有数组都知道它们自己的长度:
public static void doingSomething(){
if (i >= something.length) {
System.out.println("Method Halted!, continuing doing the next thing");
} else {
if (something[i] >= something_else) { ... }
}
}
回答by Enno Shioji
Hmm.. I think you are a little bit confused. You don't catch a method with try catch blocks. You catch Exceptions. Exceptions are more like things.
嗯.. 我觉得你有点糊涂了。你不会用 try catch 块来捕获方法。你捕捉异常。异常更像是事物。
This alone (note the capital "A" of ArrayOutOfBoundsException) will prevent your program to terminate even if that Exception is thrown. You don't need to declare a "arrayOutOfBoundsException()" method.
仅此一项(注意 ArrayOutOfBoundsException 的大写“A”)将阻止您的程序终止,即使抛出该异常。您不需要声明“arrayOutOfBoundsException()”方法。
public static void doingSomething(){
try
{
if(something[i] >= something_else);
}
catch (ArrayOutOfBoundsException e)
{
System.out.println("Method Halted!, continuing doing the next thing");
}
}
Note the little "e"? That's the reference you can use to refer to this Exception. So, you can ask things to this Exceptions using this little local variable. For example, if you want to print where the exception happened, you can do e.printStackTrace();.
注意小“e”?这是您可以用来引用此异常的参考。所以,你可以使用这个小的局部变量来询问这个异常。例如,如果要打印异常发生的位置,可以执行e.printStackTrace();.
回答by gagneet
You catch Exceptions, with a try-catch block. Not sure if you can catch methods with this.
您可以使用 try-catch 块捕获异常。不确定您是否可以使用此方法捕获方法。
public static void myMethod(){
try {
// check for some given condition
}
catch (conditionNotSatisfied e) {
System.out.println("Condition was not satisfied, you tried to do something which is not allowed");
}
}
The 'e' in the catch() is the reference used for referring to an Exception. Exception refers to this when it wishes to check your given condition and return you a warning or error about the condition not getting satisfied.
catch() 中的“e”是用于引用异常的引用。当它希望检查您的给定条件并返回有关条件未得到满足的警告或错误时,异常是指这一点。
回答by Savvas Dalkitsis
I think you mean to have the arrayOutOfBoundsException method throw the exception caused... If i understand correctly:
我认为你的意思是让 arrayOutOfBoundsException 方法抛出引起的异常......如果我理解正确:
public static void arrayOutOfBoundsExceptionMethod() throws ArrayIndexOutOfBoundsException {
\...
\ code that throws the exception
}
.....
public static void doingSomething(){
try
{
if(something[i] >= something_else);
arrayOutOfBoundsExceptionMethod();
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Method Halted!, continuing doing the next thing");
}
}
Is that what you are asking?
这就是你要问的吗?
回答by Chris Dennett
I'm trying to understand what you're asking, your terminology is wrong in places :) If you try and set an index out of bounds, you'll get a built-in exception anyway, ArrayIndexOutOfBoundsException. You can catch this and use this inside the method, or throw it using a class XX throws ArrayIndexOutOfBoundsExceptiondeclaration in the header of the method, so that the invoking method can catch it (its not required to catch an ArrayIndexOutOfBoundsExceptionas it's a RuntimeException-- i.e., nothing happens if it goes uncaught, it's unchecked.
我试图理解你在问什么,你的术语在某些地方是错误的 :) 如果你尝试将索引设置为越界,无论如何你都会得到一个内置异常,ArrayIndexOutOfBoundsException. 您可以捕获它并在方法中使用它,或者使用class XX throws ArrayIndexOutOfBoundsException方法头中的声明抛出它,以便调用方法可以捕获它(它不需要捕获它,ArrayIndexOutOfBoundsException因为它是一个RuntimeException- 即,如果它没有任何反应没有被发现,它是未经检查的。
See this wiki article for more details: http://en.wikibooks.org/wiki/Java_Programming/Throwing_and_Catching_Exceptions.
有关更多详细信息,请参阅此 wiki 文章:http: //en.wikibooks.org/wiki/Java_Programming/Throwing_and_Catching_Exceptions。
回答by fastcodejava
It is not clear what you mean by "Is it possible to catch a method". In your case, you should write your code as :
不清楚“是否可以捕获方法”是什么意思。在您的情况下,您应该将代码编写为:
if(i < something.length && something[i] >= something_else);
No ArrayOutOfBoundsExceptionis needed.
不需要ArrayOutOfBoundsException。

