小编典典

如何在 Java 中创建自定义异常类型?

all

我想在 Java 中创建一个自定义异常,我该怎么做?

...

try{

...

String word=reader.readLine();

if(word.contains(" "))
  /*create custom exception*/

}
catch(){

当我使用 创建自定义异常时throw new...,我收到错误unreported exception...must be caught or declared to be thrown


阅读 72

收藏
2022-08-24

共1个答案

小编典典

您应该能够创建一个扩展该类的自定义异常类
Exception

,例如:

class WordContainsException extends Exception
{
      // Parameterless Constructor
      public WordContainsException() {}

      // Constructor that accepts a message
      public WordContainsException(String message)
      {
         super(message);
      }
 }

用法:

try
{
     if(word.contains(" "))
     {
          throw new WordContainsException();
     }
}
catch(WordContainsException ex)
{
      // Process message however you would like
}
2022-08-24