解释用户异常处理 [英] explaining user exception handling

查看:38
本文介绍了解释用户异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

namespace ConsoleApplication1
{
    class myexception : Exception
    {
        public myexception(string str)
        {
            Console.WriteLine("user define exception" + str);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                throw new myexception("aquib");
            }
            catch (Exception e)
            {
                Console.WriteLine("exeption caught here" + e.ToString());
            }
            Console.WriteLine("last statement");
            Console.ReadKey();
        }
    }
}


此代码将执行什么操作?
我知道这是异常处理,但是它将如何工作?
我在网上搜索.但是很难理解
谁能帮帮我
在此先感谢


what will this code will do?
i know this is exception handling but how this will works?
i search on web. but its too dificult to understand
can anyone help me out
thanks in advance

推荐答案

更好的这段代码更有意义:
Better is this code which makes more sense:
namespace ConsoleApplication1
{
    class myexception : Exception
    {
        public myexception(string str)
        {
            Console.WriteLine("user define exception" + str);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //do something
                //...
                throw new myexception("aquib");
                //following code is not executed
            }
            catch (myexception e)
            {
                Console.WriteLine("myexception caught here" + e.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("general exception caught here" + e.ToString());
            }
            Console.WriteLine("last statement");
            Console.ReadKey();
        }
    }
}


使用上述代码,您可以区分捕获到的异常还是常规异常,例如.NET框架抛出.
您应该抛出自己的异常,以防您在函数中确定某些不良情况.

程序流程如下:进入"main"函数,并且在引发异常时,紧随其后的代码不会执行,因为它会跳转到适当的catch块.在上述情况下,它跳转到"catch(myexception e)".处理异常后,可以继续下一个代码.在您的情况下,它将写入输出"last statement".

请阅读这些文章以获取更多信息:
.NET中的异常处理最佳实践 [用户友好的异常处理 [


Using the above code you are able to differentiate between your exception being caught or general exceptions that e.g. the .NET framework throws.
You should throw your own exceptions in case you determine in your functions that something was bad.

The program flow is as follows:The "main" function is entered and when the exception is thrown, the code that is directly after that is not executed since it jumps to the catch block that is appropriate. In the case above it jumps to "catch(myexception e)". After handling the exception it can continue with the next code. In your case it writes to the output "last statement".

Please read these articles for some more information:
Exception Handling Best Practices in .NET[^]
User Friendly Exception Handling[^]


这篇关于解释用户异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆