如何在 Java 中创建自定义异常? [英] How to create custom exceptions in Java?

查看:43
本文介绍了如何在 Java 中创建自定义异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何在 Java 中创建自定义异常?

How do we create custom exceptions in Java?

推荐答案

要定义 checked 异常,您可以创建 java.lang.Exception.例如:

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

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);
}

您会在上面的示例中注意到 IOException 被捕获并作为 FooException 重新抛出.这是用于封装异常的常用技术(通常在实现 API 时).

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).

有时会出现您不想强制每个方法在其 throws 子句中声明您的异常实现的情况.在这种情况下,您可以创建一个未检查异常.未经检查的异常是扩展 java 的任何异常.lang.RuntimeException(它本身是 java.lang.Exception):

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 unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}

方法可以在不声明的情况下抛出或传播FooRuntimeException异常;例如

Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

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.

java.lang.Throwable 类是 Java 中可以抛出的所有错误和异常的根源.java.lang.Exceptionjava.lang.Error 都是 可扔.任何子类 Throwable 可能会被抛出或抓住.但是,捕获或抛出 Error 因为这用于表示程序员通常无法处理"的 JVM 内部错误(例如 OutOfMemoryError).同样,您应该避免捕获 Throwable,这可能会导致您捕获 错误 除了 异常s.

这篇关于如何在 Java 中创建自定义异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆