C# 语句异常处理语句

来源:互联网 发布:mac 待机快捷键 编辑:程序博客网 时间:2024/06/13 21:22
1,try....catch...finally 不会找到逻辑错误,try里面放检测代码,,catch 捕捉到的异常,怎样处理finally不管有没有异常都会执行    try catch finally  3种组合
2,finally 很顽强  return后仍然会执行
3,C 语句异常处理语句 - 风未定 - 风未定的博客
 
C 语句异常处理语句 - 风未定 - 风未定的博客
 
4,C 语句异常处理语句 - 风未定 - 风未定的博客
excption的用法C 语句异常处理语句 - 风未定 - 风未定的博客
  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 { }
}
}
}



0 0