C# ThroweException在当前上下文中不存在
在vs2010中进行一些练习 使用try/catch/finally并获得以下消息: 当前上下文中不存在抛出异常。 我是否缺少使用ThrowException的using语句C# ThroweException在当前上下文中不存在,c#,.net,C#,.net,在vs2010中进行一些练习 使用try/catch/finally并获得以下消息: 当前上下文中不存在抛出异常。 我是否缺少使用ThrowException的using语句 using System; using System.Collections.Generic; using System.Linq; using System.Text; class Program { static string[] eTypes = { "none", "simple", "index", "
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
static string[] eTypes = { "none", "simple", "index", "nested index" };
static void Main(string[] args)
{
foreach (string eType in eTypes)
{
try
{
Console.WriteLine("Main() try");
Console.WriteLine("Throwing: \"{0}\") Called.",eType);
ThrowException(eType);
Console.WriteLine("Main() try continuing");
}
catch (System.IndexOutOfRangeException e)
{
Console.WriteLine("Main System.indexoutofrange catch",
e.Message);
}
finally
{
Console.WriteLine("Main finally");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
你为什么不使用
throw new Exception(eType);
有意引发异常的语法很简单
throw new WhateverException(yourMessage, yourInnerException);
典型的异常还有构造函数重载,要么只接受消息,要么根本不接受参数。您没有定义名为
ThroweException
的方法
如果你试图提出一个异常,那不是怎么做的。你会:
throw new SomeTypeOfException(eType);
鉴于您的测试,我怀疑您想要:
throw new IndexOutOfRangeException(eType);
有关详细信息,请参阅。它不是ThroweException()函数。这是一个声明;抛出新异常(“某些消息”) 什么是通过Exception()调用的
?它不是一个内置的方法,您在哪里定义它?如果您试图学习如何处理异常,那么请学习不显示ex.Message。使用ex.ToString()获取整个异常。