习题
练习1
- 代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
int m, n;
Console.WriteLine("除法运算开始...");
Console.WriteLine();
Console.WriteLine("请输入被除数");
m = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("请输入除数");
n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("结果是:");
try
{
Console.WriteLine($"{m / n}");
}
catch(DivideByZeroException ex)
{
Console.WriteLine($"{ex.Message.ToString()}");
}
}
}
}
-
运行结果1
-
运行结果2
-
如果没有异常处理程序的运行结果
练习2
- 代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace practise2
{
public partial class Form1 : Form
{
string[] StuName =new string[10];
int i = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
try
{
StuName[i] = textBox2.Text;
i++;
textBox1.Text = textBox1.Text+textBox2.Text+" ";
textBox2.Text="";
}
catch
{
MessageBox.Show("人数超过了10个,数组越界!","我的数组异常",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
}
}
-
运行结果
练习3
- 代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace practise3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//判断是不是字符串是不是数字
private static bool IsNumberic(string oText)
{
try
{
int var1 = Convert.ToInt32(oText);
return true;
}
catch
{
return false;
}
}
private void button1_Click(object sender, EventArgs e)
{
if (!(IsNumberic(textBox1.Text)))
{
MessageBox.Show("输入的不是数字!");
}
else
{
try
{
textBox2.Text = Convert.ToString(Math.Log(Convert.ToInt32(textBox1.Text)));
if ((Convert.ToInt32(textBox1.Text)) < 0)
{
throw new LowerThan0EX("所取数小于0!");
}
else if ((Convert.ToInt32(textBox1.Text)) == 0)
{
throw new Equal0EX("所取数等于0!");
}
}
catch (LowerThan0EX ex)
{
MessageBox.Show(ex.ToString());
}
catch (Equal0EX ex)
{
MessageBox.Show(ex.ToString());
}
}
}
//自定义异常1
class LowerThan0EX : ApplicationException
{
public LowerThan0EX(string message) : base(message) { }
public override string Message
{
get
{
return base.Message;
}
}
}
//自定义异常2
class Equal0EX : ApplicationException
{
public Equal0EX(string message) : base(message) { }
public override string Message
{
get
{
return base.Message;
}
}
}
}
}
-
运行结果