如何在 Java 中创建自定义异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1754315/
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
How to create custom exceptions in Java?
提问by Suresh Chaganti
How do we create custom exceptions in Java?
我们如何在 Java 中创建自定义异常?
采纳答案by Adamski
To define a checkedexception you create a subclass (or hierarchy of subclasses) of java.lang.Exception
. For example:
要定义已检查的异常,请创建java.lang.Exception
. 例如:
public class FooException extends Exception {
public FooException() { super(); }
public FooException(String message) { super(message); }
public FooException(String message, Throwable cause) { super(message, cause); }
public FooException(Throwable cause) { super(cause); }
}
Methods that can potentially throw or propagate this exception must declare it:
可能抛出或传播此异常的方法必须声明它:
public void calculate(int i) throws FooException, IOException;
... and code calling this method must either handle or propagate this exception (or both):
...并且调用此方法的代码必须处理或传播此异常(或两者):
try {
int i = 5;
myObject.calculate(5);
} catch(FooException ex) {
// Print error and terminate application.
ex.printStackTrace();
System.exit(1);
} catch(IOException ex) {
// Rethrow as FooException.
throw new FooException(ex);
}
You'll notice in the above example that IOException
is caught and rethrown as FooException
. This is a common technique used to encapsulate exceptions (typically when implementing an API).
您会注意到在上面的示例中IOException
被捕获并重新抛出为FooException
. 这是用于封装异常的常用技术(通常在实现 API 时)。
Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an uncheckedexception. An unchecked exception is any exception that extends java.lang.RuntimeException
(which itself is a subclass of java.lang.Exception
):
有时会出现您不想强制每个方法在其 throws 子句中声明您的异常实现的情况。在这种情况下,您可以创建一个未经检查的异常。未经检查的异常是任何扩展的异常java.lang.RuntimeException
(它本身是 的子类java.lang.Exception
):
public class FooRuntimeException extends RuntimeException {
...
}
Methods can throw or propagate FooRuntimeException
exception without declaring it; e.g.
方法可以在FooRuntimeException
不声明的情况下抛出或传播异常;例如
public void calculate(int i) {
if (i < 0) {
throw new FooRuntimeException("i < 0: " + i);
}
}
Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.
未经检查的异常通常用于表示程序员错误,例如将无效参数传递给方法或试图违反数组索引边界。
The java.lang.Throwable
class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception
and java.lang.Error
are both subclasses of Throwable
. Anything that subclasses Throwable
may be thrown or caught. However, it is typically bad practice to catch or throw Error
as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError
). Likewise you should avoid catching Throwable
, which could result in you catching Error
s in addition to Exception
s.
该java.lang.Throwable
班是所有的错误和异常,可以在Java中抛出的根源。 java.lang.Exception
并且java.lang.Error
都是 的子类Throwable
。任何子类都Throwable
可能被抛出或捕获。但是,捕获或抛出通常是不好的做法,Error
因为这用于表示 JVM 内部的错误,这些错误通常不能由程序员“处理”(例如OutOfMemoryError
)。同样,您应该避免 catch Throwable
,这可能导致您Error
除了Exception
s之外还捕获s。
回答by Amber
For a checked exception:
对于已检查的异常:
public class MyCustomException extends Exception { }
Technically, anything that extends Throwable
can be an thrown, but exceptions are generally extensions of the Exception
class so that they're checked exceptions (except RuntimeException or classes based on it, which are not checked), as opposed to the other common type of throwable, Error
s which usually are not something designed to be gracefully handled beyond the JVM internals.
从技术上讲,任何扩展Throwable
都可以抛出,但异常通常是Exception
类的扩展,因此它们是检查异常(除了 RuntimeException 或基于它的类,它们不被检查),而不是其他常见的 throwable 类型,Error
s 通常不是为了在 JVM 内部之外优雅地处理而设计的。
You can also make exceptions non-public, but then you can only use them in the package that defines them, as opposed to across packages.
您也可以将异常设为非公开,但您只能在定义它们的包中使用它们,而不是跨包使用。
As far as throwing/catching custom exceptions, it works just like the built-in ones - throw via
就抛出/捕获自定义异常而言,它的工作方式与内置异常一样 - throw via
throw new MyCustomException()
and catch via
并通过
catch (MyCustomException e) { }
回答by laura
public class MyException extends Exception {
// special exception code goes here
}
Throw it as:
把它扔成:
throw new MyException ("Something happened")
Catch as:
捕捉为:
catch (MyException e)
{
// something
}