如何在自定义异常中使用构造函数

本文关键字:构造函数 自定义异常 | 更新日期: 2023-09-27 18:25:38

我正在使用自定义异常来开发MVC中的应用程序。我正在使用下面的链接来了解如何处理自定义异常。

msdn 的自定义异常链接

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace epay.Services.ExceptionClasses
{
    public class InvalidInputException : Exception
    {
    public InvalidInputException()
    {
    }
    public InvalidInputException(string message) : base(message)
    {
    }
    public InvalidInputException(string message, Exception inner) : base(message, inner)
    {
    }
    }
}

但我完全不知道如何使用这些以消息和内部异常为参数的构造函数。

我在控制器中有如下代码。。。

 [HttpPost]
        public ActionResult Create(PartyVM PartyVM)
        {
            try
            {
                PartyService partyService = new PartyService();
                var i = partyService.Insert(PartyVM);
                return RedirectToAction("SaveData", PartyVM);
            }
            catch (InvalidInputExceptione e)
            {
                CommonMethod commonMethod = new CommonMethod();
                PartyVM.AccountTypes = commonMethod.GetAccountTypes();
                TempData["error"] = e.Message.ToString() + "Error Message";
                return View("Create", PartyVM);
            }
}

如何在自定义异常中使用构造函数

异常是在thrown之前构造的。您共享的catch代码是一个例外。

您可以抛出如下异常:

throw new InvalidInputException("Invalid value for username");

InnerException属性在捕获异常时使用,但您希望将其封装在自己的异常中以提供更准确的异常信息,例如,这将验证"年龄"的string值:

public static class Validation
{
    public void ThrowIfAgeInvalid(string ageStr)
    {
        int age;
        try
        {
            // Should use int.TryParse() here, I know :)
            age = int.Parse(ageStr);
        }
        catch (Exception ex)
        {
            // An InnerException which originates to int.Parse
            throw new InvalidInputException("Please supply a numeric value for 'age'", ex);
        }
        if (age < 0 || age > 150)
        {
            // No InnerException because the exception originates to our code
            throw new InvalidInputException("Please provide a reasonable value for 'age'");
        }
    }
}

这样,在调试时,您仍然可以引用问题的原始原因。