自定义异常类在编程中是一种常见的做法,它可以帮助我们更好地处理特定于应用程序的错误情况。以下是自定义异常类通常需要遵循的一些规则:
Exception 类或其子类。Exception 类或其子类。Exception 类或其子类。__str__ 或 toString 方法__str__ 方法以返回友好的错误消息。toString 方法以返回友好的错误消息。class CustomError(Exception):
def __init__(self, message, error_code=None):
super().__init__(message)
self.error_code = error_code
def __str__(self):
return f"{self.args[0]} (Error Code: {self.error_code})"
# 使用示例
try:
raise CustomError("Something went wrong", error_code=404)
except CustomError as e:
print(e) # 输出: Something went wrong (Error Code: 404)
public class CustomException extends Exception {
private int errorCode;
public CustomException(String message, int errorCode) {
super(message);
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
@Override
public String toString() {
return super.getMessage() + " (Error Code: " + errorCode + ")";
}
}
// 使用示例
try {
throw new CustomException("Something went wrong", 404);
} catch (CustomException e) {
System.out.println(e); // 输出: Something went wrong (Error Code: 404)
}
using System;
public class CustomException : Exception
{
public int ErrorCode { get; }
public CustomException(string message, int errorCode)
: base(message)
{
ErrorCode = errorCode;
}
public override string ToString()
{
return $"{Message} (Error Code: {ErrorCode})";
}
}
// 使用示例
try
{
throw new CustomException("Something went wrong", 404);
}
catch (CustomException e)
{
Console.WriteLine(e); // 输出: Something went wrong (Error Code: 404)
}
通过遵循这些规则,你可以创建出清晰、易于理解和维护的自定义异常类。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。