zoukankan      html  css  js  c++  java
  • c# try..... catch

      功能说明:在此例中,try 块包含对可能导致异常的ProcessString()方法的调用.catch子句包含仅在屏幕上显示消息的异常处理程序,当从ProcessString内部调用throw语句时,系统查找Catch语句并显示Exception caught消息.

        class Try_Test1
        {
            static void processString(string s)
            {
                if (s == null)
                {
                    throw new ArgumentNullException();
                }

            }
            static void Main()
            {
                try
                {
                    string s = null;
                    processString(s);
                }
                catch (Exception e)
                {
                    Console.WriteLine("第二个异常被捕获{0}",e);
                }
                Console.ReadKey();
            }
        }

     此例使用了两个catch语句,最先出现的是最特定的异常被捕获.

     class Try_Test2
        {
            static void processString(string s)
            {
                if (s == null)
                {
                    throw new ArgumentNullException();
                }

            }
            static void Main()
            {
                try
                {
                    string s = null;
                    processString(s);
                }
                catch (ArgumentNullException e)
                {
                    Console.WriteLine("第一个异常被获{0}.", e);
                }
                catch (Exception e)
                {
                    Console.WriteLine("第二个异常被捕获{0}",e);
                }
                Console.ReadKey();
            }
        }

     //异常处理语句——try-finally使用

     //功能说明:在此例中,有一个导致异常的效转换语句,收到一条运行时的错误信息时,Finally语句块还是会执行.

        public class  Finally_Test1
        {
            static void Main()
            {
                int i = 123;
                string s = "string test";
                object o = s;
                try
                {
                    i = (int)o; //转换无效
                }
                catch (Exception e)
                {
                    Console.WriteLine("转换无效");

                }
                finally
                {
                    Console.WriteLine("i={0}", i);//但是finally还是最终会执行。
                }
                Console.ReadKey();
            }

  • 相关阅读:
    转:wcf大文件传输解决之道(1)
    转:WCF传送二进制流数据基本实现步骤详解
    创建一个简单的WCF程序2——手动开启/关闭WCF服务与动态调用WCF地址
    创建一个简单的WCF程序
    转:【专题十二】实现一个简单的FTP服务器
    转:【专题十一】实现一个基于FTP协议的程序——文件上传下载器
    转:【专题十】实现简单的邮件收发器
    转:【专题九】实现类似QQ的即时通信程序
    转:【专题八】P2P编程
    转:【专题七】UDP编程补充——UDP广播程序的实现
  • 原文地址:https://www.cnblogs.com/print/p/3389373.html
Copyright © 2011-2022 走看看