捕获并处理
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string str1 = Console.ReadLine();
string str2 = Console.ReadLine();
int result = Add(str1, str2);
Console.WriteLine(result);
}
static int Add(string str1, string str2)
{
int n1 = 0;
int n2 = 0;
bool hasError = false;
try
{
n1 = int.Parse(str1);
n2 = int.Parse(str2);
}
catch (ArgumentException e)
{
Console.WriteLine("ArgumentException");
Console.WriteLine(e.Message);
hasError = true;
}
catch (FormatException e)
{
Console.WriteLine("FormatException");
Console.WriteLine(e.Message);
hasError = true;
}
catch (OverflowException e)
{
Console.WriteLine("OverflowException");
Console.WriteLine(e.Message);
hasError = true;
}
catch (Exception e)
{
Console.WriteLine("exception");
hasError = true;
}
finally
{
if (hasError)
{
Console.WriteLine("程序发生异常");
}
}
return n1 + n2;
}
}
}
抛出异常
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string str1 = Console.ReadLine();
string str2 = Console.ReadLine();
int result = 0;
try
{
result = Add(str1, str2);
}
catch (FormatException)
{
Console.WriteLine("格式异常");
}
Console.WriteLine(result);
}
static int Add(string str1, string str2)
{
int n1 = 0;
int n2 = 0;
try
{
n1 = int.Parse(str1);
n2 = int.Parse(str2);
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
}
catch (FormatException e)
{
throw;
}
catch (Exception e)
{
Console.WriteLine("exception");
}
return n1 + n2;
}
}
}