.NET Framework中的所有"异常"派生自"System.Exception"类。
异常对象用于描述发生错误,然后用throw关键字抛出。
throw是C#中的保留关键字。
异常对象具有一些重要的属性。例如:
| 属性 | 描述 |
|---|---|
| Message | 提供有关消息的详细信息。 |
| StackTrace | 提供函数堆栈来显示抛出异常的位置。 |
| Targetsite | 显示引发异常的方法。 |
在C#中抛出异常语法
Catch(Exception e)
{
...
Throw e
}
在C#中抛出异常示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class ThrowExample
{
public static void Ma(Int32 marks)
{
if (marks < 0)
{
//如果marks小于零,则抛出超出范围的参数异常。
throw new ArgumentOutOfRangeException("marks不能为负数");
}
}
public static void Main()
{
try
{
Ma(-2);
}
catch (Exception e)
{
Console.WriteLine(String.Concat(e.StackTrace, e.Message));
Console.ReadLine();
}
}
日期:2020-04-11 23:03:54 来源:oir作者:oir
