简体   繁体   English

未处理的异常错误C#

[英]An unhandled exception error c#

This is so confusing... I have a class with set and get methods here is a few of them: 这真令人困惑...我有一个带有set和get方法的类,这里是其中的一些:

public string Naziv
    {
        get { return naziv; }
        set
        {
            naziv = value;
            if (naziv == "")
            {
                throw new Exception("Morate uneti naziv radnog mesta.");
            }
            else if (naziv.Length < 5)
            {
                throw new Exception("Naziv mora biti duzi od 5 karaktera.");
            }

        }
    }

This one works perfect. 这一作品完美。 But this one: 但是这个:

public string RadnoVreme1
    {
        get { return radnovreme1; }
        set
        {
            radnovreme1 = value;
            if (IsValid(radnovreme1) == false)
            {
                //Console.WriteLine("1:FALSE ");
                throw new Exception("Radno vreme mora biti u formatu '12:00h-20:00h'.");

            }
        }
    }
    static bool IsValid(string value)
    {
        return Regex.IsMatch(value, @"^\d{2}:\d{2}h-\d{2}:\d{2}h");
    }

Breaks my solution with an error: 导致我的解决方案出现错误:

An unhandled exception of type 'System.Exception' occurred in Evidencija.exe Additional information: Radno vreme mora biti u formatu '12:00h-20:00h'. Evidencija.exe中发生了'System.Exception'类型的未处理异常。其他信息:格式为'12:00h-20:00h'。

Another thing. 另一件事。 When un-commenting ' Console.WriteLine ' line and commenting out ' throw new Exception ' one I get this output: 当取消注释' Console.WriteLine '行并注释掉' throw new Exception '时,我得到以下输出:

1:FALSE
1:FALSE 
1:FALSE 
The thread 0x1748 has exited with code 0 (0x0).

Why is this running 3 times? 为什么要运行3次? Is it because I already have 3 stored objects in my DB? 是因为我的数据库中已经有3个存储对象了吗? Shouldn't this only be running when creating new object? 这不应该仅在创建新对象时运行吗?

It's not breaking your solution, it's throwing the exception you tell it to throw which doesn't get caught by anything else in your code. 它并没有破坏您的解决方案,而是抛出了您告诉它引发的异常,该异常不会被代码中的其他任何事物捕获。 In the first example, apparently neither conditional case is being hit so no exception is thrown and your program continues executing. 在第一个示例中,显然没有任何条件情况发生,因此不会引发异常,并且程序将继续执行。 If you are setting the property RadnoVreme1 multiple times elsewhere in your code you will see multiple lines of output such as you describe. 如果您在代码的其他位置多次设置属性RadnoVreme1,则会看到多行输出,如您所描述。 The reason the last one exits is because the condition is hit ( IsValid(radnovreme1) == false ) which throws the exception. 最后一个退出的原因是因为条件被击中( IsValid(radnovreme1) == false ),从而引发了异常。 In the other three calls that condition does not get hit. 在其他三个呼叫中,该条件未达到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM