从自定义异常类获取“消息”

编程入门 行业动态 更新时间:2024-10-12 12:24:56
本文介绍了从自定义异常类获取“消息”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

此问题是指此处的答案。我需要访问自定义异常的消息。

This question refers to an answer here. I need to access message of a custom exception. Is this possible?

我认为直接调用消息就足够了,如下面的示例:

I thought that directly calling message will suffice as in this example:

class MyCustomError < StandardError attr_reader :object def initialize(object) @object = object puts message end end

但这不是我期望的。它给了我一些字符串,例如:

but this is not what I expected it to be. It gave me some string like:

"MyModuleNameHere::MyCustomExceptionClassNameHere"

而不是:

"a message"

我的直觉倾向于否定,因为 initialize 构造函数不会接受消息 文本。

My intuition is leaning towards no, since the initialize constructor does not take the "a message" text.

推荐答案

通过消息并调用 super 通常会接收一条消息,例如 StandardError.new( oh no)。

You can pass the message and call super which will normally take a message, e.g. StandardError.new("oh no").

class MyCustomError < StandardError def initialize(message, object) # ... super(message) end end MyCustomError.new("Oh no", thing).message # => "Oh no"

这本有关Ruby异常的电子书非常值得: exceptionalruby/

This ebook on Ruby exceptions is well worth it: exceptionalruby/

更多推荐

从自定义异常类获取“消息”

本文发布于:2023-11-27 20:01:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639403.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   异常   消息

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!