Java 程序:创建自定义异常

要理解此示例,您应了解以下Java编程主题


示例 1:创建自定义已检查异常的Java程序

import java.util.ArrayList;
import java.util.Arrays;

// create a checked exception class
class CustomException extends Exception {
  public CustomException(String message) {
    // call the constructor of Exception class
    super(message);
  }
}

class Main {

  ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "Python", "JavaScript"));

  // check the exception condition
  public void checkLanguage(String language) throws CustomException {

    // throw exception if language already present in ArrayList
    if(languages.contains(language)) {
      throw new CustomException(language + " already exists");
    }
    else {
      // insert language to ArrayList
      languages.add(language);
      System.out.println(language + " is added to the ArrayList");
    }
  }

  public static void main(String[] args) {

    // create object of Main class
    Main obj = new Main();

    // exception is handled using try...catch
    try {
      obj.checkLanguage("Swift");
      obj.checkLanguage("Java");
    }

    catch(CustomException e) {
      System.out.println("[" + e + "] Exception Occured");
    }
  }
}

输出

Swift is added to the ArrayList
[CustomException: Java already exists] Exception Occured

在上面的示例中,我们扩展了Exception类以创建名为CustomException的自定义异常。在此,我们使用super关键字从CustomException类调用Exception类的构造函数

checkLanguage()方法中,我们检查了异常条件,如果发生异常,则try..catch块会处理该异常。

这里,这是一个已检查异常。我们也可以创建Java中的未检查异常类。


示例 2:创建自定义未检查异常类

import java.util.ArrayList;
import java.util.Arrays;

// create a unchecked exception class
class CustomException extends RuntimeException {
  public CustomException(String message) {
    // call the constructor of RuntimeException
    super(message);
  }
}

class Main {

  ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "Python", "JavaScript"));

  // check the exception condition
  public void checkLanguage(String language) {

    // throw exception if language already present in ArrayList
    if(languages.contains(language)) {
      throw new CustomException(language + " already exists");
    }
    else {
      // insert language to ArrayList
      languages.add(language);
      System.out.println(language + " is added to the ArrayList");
    }
  }

  public static void main(String[] args) {

    // create object of Main class
    Main obj = new Main();

    // check if language already present
    obj.checkLanguage("Swift");
    obj.checkLanguage("Java");
  }
}

输出

Swift is added to the ArrayList
Exception in thread "main" CustomException: Java already exists
        at Main.checkLanguage(Main.java:21)
        at Main.main(Main.java:37)

在上面的示例中,我们扩展了RuntimeException类以创建自定义未检查异常类。

这里,您会注意到,我们没有声明任何try...catch块。这是因为未检查异常是在运行时检查的。

除此之外,未检查异常的其他功能与上面提到的程序类似。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战