如何在 Java 中创建自定义异常类型? [英] How to create a custom exception type in Java?

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

问题描述

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

I would like to create a custom exception in Java, how do I do it?

...

try{

...

String word=reader.readLine();

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

}
catch(){

当我使用 throw new... 创建我的自定义异常时,我得到错误 unreported exception... must be catch or Declaration to be throw

When I create my custom exception with throw new..., I obtain the error unreported exception...must be caught or declared to be thrown

推荐答案

您应该能够创建一个自定义异常类来扩展 Exception 类,例如:

You should be able to create a custom exception class that extends the Exception class, for example:

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
}

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

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