异常处理语句
来源:互联网 发布:黄品源 知乎 编辑:程序博客网 时间:2024/05/17 05:15
1.try---catch语句
try
{
被监控的代码
}
catch(异常类名 异常变量名)
{
异常处理
}
eg:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 例9_1_try__catch的使用
{
class Program
{
static void Main(string[] args)
{
try
{
object obj = null ;
int N = (int)obj;
}
catch (Exception ex)
{
Console.WriteLine("捕获异常:"+ex);
}
Console.ReadLine();
}
}
}
eg2:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 例9_2try_catch的使用
{
class Program
{
static void Main(string[] args)
{
try
{
checked
{
int Inum1;
int Inum2;
int num;
Inum1 = 6000000;
Inum2 = 6000000;
num = Inum1 + Inum2;
Console.WriteLine(num);
}
}
catch (OverflowException) //捕获在算术运算时导致溢出时引发的异常
{
Console.WriteLine("引发OverflowException异常:");
}
Console.ReadLine();
}
}
}
2.throw语句:
eg:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 例9_3_throw的使用
{
class Program
{
class test
{
public int MyInt(string a, string b)
{
int int1;
int int2;
int num;
try
{
int1 = int.Parse(a);
int2 = int.Parse(b);
if (int2 == 0)
{
throw new DivideByZeroException();
}
num = int1 / int2;
return num;
}
catch(DivideByZeroException de)
{
Console.WriteLine("用零除整数发生异常!");
Console.WriteLine(de.Message) ;
return 0;
}
}
}
static void Main(string[] args)
{
try
{
Console.WriteLine("请输入分子:");
string str1 = Console.ReadLine();
Console.WriteLine("请输入分母:");
string str2 = Console.ReadLine();
test tt = new test();
Console.WriteLine("分子除以分母的值:" + tt.MyInt(str1, str2));
}
catch (FormatException)
{
Console.WriteLine("请输入数字格式数据");
}
Console.ReadLine();
}
}
}
3.try--catch--finally语句
try
{
被监控的代码
}
catch(异常类名 异常变量名)
{
异常处理
}
finally
{
程序代码
}
eg:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 例9_4_try__catch__finally语句
{
class Program
{
static void Main(string[] args)
{
string str = "用一生下载你";
object obj = str;
try
{
int i = (int)obj;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("程序执行完毕...");
}
Console.ReadLine();
}
}
}
- C# 语句异常处理语句
- 异常处理语句
- 动态sql语句 异常处理
- C#的异常处理语句
- try语句和异常处理
- 异常处理的try-catch-finally语句
- JAVA-使用异常处理语句的注意事项
- 异常处理相关 try/finally语句
- sql语句处理单引号,解决查询异常
- sql/plus循环语句和异常处理
- C#的throw异常处理语句
- java 异常处理的语句执行
- C#中异常处理语句Finally
- try语句块和异常处理
- 使用try...catch语句处理异常
- C++ try语句块和异常处理
- 分页查询MySql语句异常处理
- 【C++】try 语句捕获异常,catch子句处理异常
- 结构
- [STL]hdu5233
- win10 10074版内存居高不下的解决办法
- Memcached客户端性能评测报告
- Quartz 2D基本介绍
- 异常处理语句
- win10 10074版本qq显示问题
- C++类与对象(3) - 空class&struct的大小
- C# 多线程并发编程资料汇总学习
- 职业选择
- 关于螺旋填数的理解
- 微信WIFI,帮你做好客流量统计
- Quartz 2D基本绘图
- Memcached哈希性能优化(八)——总结报告