• 06、C#异常处理


    一、什么叫异常,就是程序可能没有错误,在程序运行过程中发生错误。比如输入错误,输入的类型不一样,被零除。

    二、语法:

      try

         {

         可能会发生错误的语句; 

         }

      catch

         {

           处理异常语句;

         }

    三、finally关键字是收尾工作,管有没有异常都要执行。

    四、throw关系字,人为的加一个提示,抛出一个异常。

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace _09
    {
        public partial class Form1 : Form
        {
            private object textbox4;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                try
                {
                    int x, y, res;
                    x = int.Parse(textBox3.Text);
                    y = int.Parse(textBox4.Text);
    
                    switch (comboBox2.Text)
                    {
                        case "+":
                            res = x + y;
                            break;
                        case "-":
                            res = x - y;
                            break;
                        case "*":
                            res = x * y;
                            break;
                        case "/":
                            res = x / y;
                            break;
                        default:
                            res = 9999;
                            break;
                    }
    
                    label4.Text = res.ToString();
                    if (res > 10)
                        throw new ApplicationException("throw抛出的异常");
    
                }
                catch (FormatException fe)
                {
                    MessageBox.Show(fe.Message);
                    return;
                }
                catch (OverflowException ofe)
                {
    
                    MessageBox.Show(ofe.Message);
                    return;
                }
                catch (DivideByZeroException dze)
                {
    
                    MessageBox.Show(dze.Message);
                    return;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
                finally
                {
                    MessageBox.Show("最后者会执行");
                }
                }
        }
    }

      

  • 相关阅读:
    maven项目下出现java.lang.ClassNotFoundException: ContextLoader异常
    jquery使用post方法传值
    商品筛选条件
    商品的上架
    使用fckeditor上传多张图片
    多选删除
    升讯威 .Net WinForm 开源控件使用——c#
    设置label(标签)控件的背景颜色为透明
    鼠标拖动控件跟随——C#
    Chart控件系列教程——c#
  • 原文地址:https://www.cnblogs.com/zytr/p/14728520.html
Copyright © 2020-2023  润新知