自定义一个异常类MyException(继承Exception),重写父类中的toString方法,做测试,创建一个MyException对象,抛出
时间: 2024-05-12 15:13:05 浏览: 17
下面是自定义异常类MyException的代码:
```python
class MyException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return f"MyException: {self.message}"
```
我们重写了父类中的`__str__`方法,使得在抛出异常时可以输出更加有用的信息。
接下来,我们可以测试一下这个自定义异常类:
```python
try:
raise MyException("这是一个自定义的异常")
except MyException as e:
print(e)
```
输出结果为:
```
MyException: 这是一个自定义的异常
```
可以看到,我们成功地抛出了一个自定义的异常,并且输出了我们定义的错误信息。
相关问题
写一个异常类MyException,继承自标准库中的exception基类
下面是一个继承自 exception 基类的 MyException 异常类的示例代码:
```c++
#include <exception>
#include <string>
class MyException : public std::exception {
public:
MyException(const std::string& message) : m_message(message) {}
virtual const char* what() const noexcept {
return m_message.c_str();
}
private:
std::string m_message;
};
```
这个类定义了一个构造函数,它接受一个字符串参数 message,用于描述异常的信息。在构造函数中,我们将 message 存储到类的私有成员变量 m_message 中。
类中还重载了 exception 基类中的 what() 函数,它用于返回异常描述信息的 C 字符串。在这里,我们直接返回 m_message.c_str()。
这个类可以用于抛出自定义异常,比如:
```c++
try {
// some code that may throw an exception
throw MyException("Something went wrong");
}
catch (const MyException& e) {
std::cerr << "Caught MyException: " << e.what() << std::endl;
}
catch (const std::exception& e) {
std::cerr << "Caught standard exception: " << e.what() << std::endl;
}
catch (...) {
std::cerr << "Caught unknown exception" << std::endl;
}
```
在这个示例中,我们在 try 块中抛出了一个 MyException 异常,并在 catch 块中捕获了它。如果程序中还有其他异常被抛出,我们也可以在 catch 块中捕获它们。
自定义一个编译异常MyException,并编写MyException Test测试类验证
好的,让我来演示一下。
首先,我们需要创建一个编译异常类MyException,代码如下:
```
public class MyException extends Exception {
public MyException() {
super();
}
public MyException(String message) {
super(message);
}
}
```
接下来,我们可以编写一个测试类MyExceptionTest,用于验证MyException是否能够正常工作,代码如下:
```
public class MyExceptionTest {
public static void main(String[] args) {
try {
throw new MyException("This is a custom exception");
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}
```
在上面的测试类中,我们通过throw语句抛出一个自定义异常MyException,并在catch语句块中捕获该异常并输出异常信息。
现在我们可以运行MyExceptionTest类,验证自定义异常MyException是否能够正常工作了。