感谢关于这个问题的输入,我决定让我的Create()方法抛出异常,这样Jon Skeet说,你不必在任何地方处理它们,只能让它们冒泡,似乎是最好的方法适用于大型应用.
所以现在用这段代码创建我的类的实例:
try
{
SmartForms smartForms = SmartForms.Create("ball");
smartForms.Show();
}
catch (CannotInstantiateException ex)
{
Console.WriteLine("Item could not be instantiated: {0}", ex.Message);
}
Run Code Online (Sandbox Code Playgroud)
自定义异常:
using System;
namespace TestFactory234.Exceptions
{
class CannotInstantiateException : Exception
{
}
}
Run Code Online (Sandbox Code Playgroud)
我如何知道要使用哪个Exception类?
在上面的例子中,我创建了自己的Exception,因为我不知道从哪里获取"所有系统异常"列表,或者是否存在"无法实例化对象"或者是否具有其他含义使用它等等.选择一个异常类型对我来说似乎总是这样一个任意的过程,所以创建我自己似乎是最好的想法.
或者我错过了一些关于异常的事情?决定使用哪种Exception类型还涉及哪些其他含义?
我有一个关于如何发送自定义异常作为FaultException的问题.当我使用像ArgumentException这样的系统异常时,它可以工作,但是如果我将它更改为我的自定义异常"TestException",它就会失败.当我尝试添加它时,我无法获得服务引用的配置.
作品:
[OperationContract]
[FaultContract(typeof(ArgumentException))]
[TransportChannel TestMethod ();
public Void TestMethod()
{
throw new FaultException<ArgumentException>(new ArgumentException("test"), new FaultReason("test"));
}
Run Code Online (Sandbox Code Playgroud)
不起作用:
[OperationContract]
[FaultContract(typeof(TestException))]
[TransportChannel TestMethod ();
public Void TestMethod()
{
throw new FaultException<TestException>(new TestException("test"), new FaultReason("test"));
}
Run Code Online (Sandbox Code Playgroud)
我的"TestException"看起来像这样:
[Serializable()]
public class TestException: Exception
{
public TestException () : base() { }
public TestException (string message) : base(message) { }
public TestException (string message, Exception innerException) : base(message, innerException) { }
public TestException (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
} …Run Code Online (Sandbox Code Playgroud) wcf exception-handling exception custom-exceptions faultexception
实现自定义异常的优缺点如下:
创建一个枚举,在其描述中表示错误消息:
public class Enums
{
public enum Errors
{
[Description("This is a test exception")]
TestError,
...
}
}
Run Code Online (Sandbox Code Playgroud)
创建自定义异常类:
public class CustomException : ApplicationException
{
protected Enums.Errors _customError;
public CustomException(Enums.Errors customError)
{
this._customError = customError;
}
public override string Message
{
get
{
return this._customError!= Enums.Errors.Base ? this.customError.GetDescription() : base.Message;
}
}
}
Run Code Online (Sandbox Code Playgroud)
该GetDescription方法是枚举扩展方法,它使用反射获取枚举描述.这样,我可以抛出异常,如:
throw new customException(enums.Errors.TestError);
Run Code Online (Sandbox Code Playgroud)
并在catch块中向用户显示如下:
Console.WriteLn(ex.Message);
Run Code Online (Sandbox Code Playgroud)
我见过MVP推荐的这种方法.这种方法对以下方面有什么好处:
WebServiceException班级,AuthenticationException班级等) 谢谢.
我应该何时创建自己的自定义异常类而不是使用.Net提供的异常类?
我应该从哪个基础异常类中派生出来,为什么?
我一直在尝试编写自己的自定义构造函数,但是获取有关base()构造函数的错误.我一直在寻找如何解决这个错误,但没有发现任何内容,互联网上的所有示例都显示与我的几乎相同的代码.
Whole Exception.cs内容:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace RegisService
{
public class Exceptions : Exception
{
}
public class ProccessIsNotStarted : Exceptions
{
ProccessIsNotStarted()
: base()
{
//var message = "Formavimo procesas nestartuotas";
//base(message);
}
ProccessIsNotStarted(string message)
: base(message) {}
ProccessIsNotStarted(string message, Exception e)
: base(message, e) {}
}
}
Run Code Online (Sandbox Code Playgroud)
第一次重载base()正在工作,没有抛出任何错误.第二次和第三次重载告诉我:
"RegisService.Exceptions不包含带有1(2)个参数的构造函数"
我试图解决错误的另一种方法:
ProccessIsNotStarted(string message)
{
base(message);
}
ProccessIsNotStarted(string message, Exception e)
{
base(message, e);
}
Run Code Online (Sandbox Code Playgroud)
这一次,VS告诉我:
"使用关键字'base'在此上下文中无效"
那么,问题出在哪里?看起来base()构造函数有一些奇怪的重载或我以不恰当的方式调用它?
我正在我的 python 代码中自定义异常。我已经将异常类继承到其他类,现在将一些自定义错误定义为从我的自定义异常类派生的类,如下所示:
class DataCollectorError(Exception): pass
class ParamNullError(DataCollectorError) : pass
class ParamInvalidTypeError(DataCollectorError) : pass
Run Code Online (Sandbox Code Playgroud)
我在我的 python 函数中引发了这些异常,例如:
def READ_METER_DATA (regIndex, numRegisters, slaveUnit):
try:
if not regIndex:
raise ParamNullError, "register index is null"
if not numRegisters:
raise ParamNullError, "number of registers should not be null"
if not slaveUnit:
raise ParamNullError, "Meter Id should not be null"
Run Code Online (Sandbox Code Playgroud)
并记录错误,如:
except DataCollectorError as d:
lgr.error('DataCollector Error(READ_METER_DATA): '+d.args[0])
print 'DataCollector Error:(READ_METER_DATA)', d.args[0]
except:
lgr.error('Unexpected Error: ', sys.exc_info())
print 'Unexpected Error: ', sys.exc_info()
pass
Run Code Online (Sandbox Code Playgroud)
但这违背了单元测试脚本的目的,因为它不会在我的单元测试脚本知道异常之前是否被我的 catch …
python inheritance exception-handling exception custom-exceptions
我正在尝试使用Jackson库中的writeValueAsString()方法序列化Java中的自定义Exception。我打算通过HTTP将其发送到另一台计算机。这是局部工作的,因为序列化后并非所有字段都包含在JSON中。顶级异常Throwable实现了Serializable接口,并且还具有一些构造函数,这些构造函数添加有关要序列化的内容的信息。我想真相就在这里。请提供一些建议。这是我的自定义异常代码:
import java.io.Serializable;
public class MyException extends RuntimeException{
private static String type = null;
private static String severity = null;
// somewhere on google I red that should use setters to make serialize work
public static void setType(String type) {
MyException.type = type;
}
public static void setSeverity(String severity) {
MyException.severity = severity;
}
public MyException(String message) {
super(message);
}
}
Run Code Online (Sandbox Code Playgroud)
我在代码中使用的某处:
MyException exc = new MyException("Here goes my exception.");
MyException.setType(exc.getClass().getSimpleName());
MyException.setSeverity("Major");
throw exc;
Run Code Online (Sandbox Code Playgroud)
在其他地方,我有:
ObjectMapper mapper = new ObjectMapper(); …Run Code Online (Sandbox Code Playgroud) 我的代码覆盖率已将我的自定义异常列为 0 测试覆盖率。我正在使用 MsTest、Moq 和 Fluentassertions。是否有针对自定义异常的适当单元测试?
这是我的异常类
public class ConfigurationNotFoundException : Exception
{
public ConfigurationNotFoundException()
{
}
public ConfigurationNotFoundException(string message) : base(message)
{
}
public ConfigurationNotFoundException(string message, Exception innerException) : base(message, innerException)
{
}
protected ConfigurationNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试定义自己的自定义异常.基本上我想防止用户在年龄小于16时被创建.接下来我已经提出了一些讨论/问题.
public enum Code {
USER_INVALID_AGE("The user age is invalid");
private String message;
Code(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
Run Code Online (Sandbox Code Playgroud)
例外类:
public class TrainingException extends RuntimeException {
private Code code;
public TrainingException(Code code) {
this.code = code;
}
public Code getCode() {
return code;
}
public void setCode(Code code) {
this.code = code;
}
}
Run Code Online (Sandbox Code Playgroud)
在Validator包中,我有以下内容:
public class UserValidator implements Validator<User> {
/** {@inheritDoc} */
@Override
public void validate(User type) {
if …Run Code Online (Sandbox Code Playgroud) 发生异常时如何显示相应的错误信息。
假设在 GET 方法期间,如果未找到数据,则应显示自定义异常消息。
同样,如果我们试图删除不可用的数据。
Car.java
package com.car_rental_project.car_project;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Car {
@Id
private String id;
private String modelname;
private String type;
private String year_of_registration;
private String seating_capacity;
private String cost_per_day;
private String milleage;
private String pincode;
private String contact_number;
private String email;
public Car() {
}
public Car(String id, String modelname, String type, String year_of_registration, String seating_capacity,String cost_per_day, String milleage, String pincode, String contact_number, String email) {
super();
this.id = id;
this.modelname = modelname; …Run Code Online (Sandbox Code Playgroud) exception ×6
c# ×5
.net ×2
java ×2
base ×1
inheritance ×1
jackson ×1
json ×1
mstest ×1
python ×1
spring-boot ×1
unit-testing ×1
wcf ×1