Java中如何实现用户定义的自定义异常?

2021年3月29日18:41:26 发表评论 803 次浏览

Java为我们提供了创建我们自己的异常的工具, 这些异常基本上是的派生类。例外。例如, 以下代码中的MyException扩展了Exception类。

我们将字符串传递给超类的构造函数-Exception, 该异常是在创建的对象上使用" getMessage()"函数获得的。

// A Class that represents use-defined expception
class MyException extends Exception
{
     public MyException(String s)
     {
         // Call constructor of parent Exception
         super (s);
     }
}
  
// A Class that uses above MyException
public class Main
{
     // Driver Program
     public static void main(String args[])
     {
         try
         {
             // Throw an object of user defined exception
             throw new MyException( "GeeksGeeks" );
         }
         catch (MyException ex)
         {
             System.out.println( "Caught" );
  
             // Print the message from MyException object
             System.out.println(ex.getMessage());
         }
     }
}

输出如下:

Caught
GeeksGeeks

在上面的代码中, MyException的构造函数需要一个字符串作为其参数。该字符串使用super()传递给父类Exception的构造函数。的构造函数例外也可以在没有参数的情况下调用class, 并且对super的调用不是强制性的。

// A Class that represents use-defined expception
class MyException extends Exception
{
  
}
  
// A Class that uses above MyException
public class setText
{
     // Driver Program
     public static void main(String args[])
     {
         try
         {
             // Throw an object of user defined exception
             throw new MyException();
         }
         catch (MyException ex)
         {
             System.out.println( "Caught" );
             System.out.println(ex.getMessage());
         }
     }
}

输出如下:

Caught
null

如果你喜欢lsbin并希望做出贡献, 那么你也可以写一篇文章并将你的文章邮寄到lsbin0@163.com。查看你的文章出现在lsbin主页上, 并帮助其他开发者。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: