如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:19:24  来源:igfitidea点击:

How to create custom exceptions in Java?

javaexception

提问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 IOExceptionis 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 FooRuntimeExceptionexception 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.Throwableclass is the root of all errors and exceptions that can be thrown within Java. java.lang.Exceptionand java.lang.Errorare both subclasses of Throwable. Anything that subclasses Throwablemay be thrown or caught. However, it is typically bad practice to catch or throw Erroras 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 Errors in addition to Exceptions.

java.lang.Throwable班是所有的错误和异常,可以在Java中抛出的根源。 java.lang.Exception并且java.lang.Error都是 的子类Throwable。任何子类都Throwable可能被抛出或捕获。但是,捕获或抛出通常是不好的做法,Error因为这用于表示 JVM 内部的错误,这些错误通常不能由程序员“处理”(例如OutOfMemoryError)。同样,您应该避免 catch Throwable,这可能导致您Error除了Exceptions之外还捕获s。

回答by Amber

For a checked exception:

对于已检查的异常:

public class MyCustomException extends Exception { }

Technically, anything that extends Throwablecan be an thrown, but exceptions are generally extensions of the Exceptionclass 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, Errors which usually are not something designed to be gracefully handled beyond the JVM internals.

从技术上讲,任何扩展Throwable都可以抛出,但异常通常是Exception类的扩展,因此它们是检查异常(除了 RuntimeException 或基于它的类,它们不被检查),而不是其他常见的 throwable 类型,Errors 通常不是为了在 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
}