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

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

问题描述

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

How do we create custom exceptions in Java?

推荐答案

要定义已检查例外,您需要创建 <$ c的子类(或子类的层次结构) $ C> 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 class是所有错误的根源和可以在Java中抛出的异常。 java.lang.Exception java.lang.Error 都是 Throwable 。任何子类 Throwable 可能会被抛出或被抓住。但是,捕获或抛出 <$通常是不好的做法。 c $ c>错误 ,因为它用于表示JVM内部通常无法由程序员处理的错误(例如 OutOfMemoryError )。同样,你应该避免捕捉 Throwable ,这可能会导致您捕获 错误 /lang/Exception.htmlrel =noreferrer> 异常 s。

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 Errors in addition to Exceptions.

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

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