一、什么叫异常,就是程序可能没有错误,在程序运行过程中发生错误。比如输入错误,输入的类型不一样,被零除。
二、语法:
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)
thrownew 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("最后者会执行");
}
}
}
}
原文:https://www.cnblogs.com/zytr/p/14728520.html
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!