您的位置:首页 > 编程语言 > C#

C# 语句异常处理语句

2016-04-21 18:49 555 查看
1,try....catch...finally 不会找到逻辑错误,try里面放检测代码,,catch 捕捉到的异常,怎样处理finally不管有没有异常都会执行    try catch finally  3种组合2,finally 很顽强  return后仍然会执行3,

 

 4,

excption的用法

  exception是所有异常的父类5,自定义异常错误例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 自定义异常
{
class Triangle
{
public int a;
public int b;
public int c;
public int getCircumference()
{
if (a + b <=c || a + c <=b || b + c <=a) throw new Myexception();
return a + b + c;
}
public void showInfo()
{
if (a + b <= c || a + c <= b || b + c <= a) throw new Myexception();
Console.WriteLine("三边长为{0},{1},{2}", a, b, c);
}
}
class Myexception:Exception
{
public Myexception(): base("InvalidTriangleException")
{

}
//public Myexception(string message): base(message)
//{

//}

//public Myexception (string message, Exception inner) : base(message, inner)
//{

//}
}
class Program
{
static void Main(string[] args)
{
Triangle t=new Triangle ();
t.a = int.Parse(Console.ReadLine());
t.b = int.Parse(Console.ReadLine());
t.c = int.Parse(Console.ReadLine());
try
{
Console.WriteLine(t.getCircumference());
t.showInfo();
}
catch(Myexception me)
{
Console.WriteLine(me.Message + "异常!");
}
finally
{
}
}
}
}

捕获异常的例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication44
{
class Program
{
static void Main(string[] args)
{
int[] a = new int[4];
try
{
for (int i = 0; i < 5; i++)
{
a[i] = int.Parse(Console.ReadLine());
}
}
catch (Exception e1) ///此处Exception 可以具体到子类
{
Console.WriteLine( e1.Message+"异常!");
}
finally { }
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: