可以通过 MSDN 查方法相应的异常。
如 Int32.Parse 方法 (String) 就有以下异常。
粗略的处理异常:
static void Main(string[] args)
{
Calculator c = new Calculator();
Console.WriteLine(c.Add("abc","100"));
}
}
class Calculator
{
public int Add(string arg1,string arg2)
{
int a = 0;
int b = 0;
try
{
a = int.Parse(arg1);
b = int.Parse(arg2);
}
catch
{
Console.WriteLine("Your argument(s) have error!");
}
int result = a + b;
return result;
}
}
精确的处理异常:
class Program
{
static void Main(string[] args)
{
Calculator c = new Calculator();
Console.WriteLine(c.Add(null,"100"));
}
}
class Calculator
{
public int Add(string arg1,string arg2)
{
int a = 0;
int b = 0;
try
{
a = int.Parse(arg1);
b = int.Parse(arg2);
}
catch(ArgumentNullException)
{
Console.WriteLine("Your argument(s) are null.");
}
catch(FormatException)
{
Console.WriteLine("Your argument(s) are not number.");
}
catch (OverflowException)
{
Console.WriteLine("Out of rangle!");
}
int result = a + b;
return result;
}
}
class Program
{
static void Main(string[] args)
{
Calculator c = new Calculator();
Console.WriteLine(c.Add("9999999999999999999999999999","100"));
}
}
class Calculator
{
public int Add(string arg1,string arg2)
{
int a = 0;
int b = 0;
try
{
a = int.Parse(arg1);
b = int.Parse(arg2);
}
catch(ArgumentNullException ane)
{
Console.WriteLine(ane.Message);
}
catch(FormatException fe)
{
Console.WriteLine(fe.Message);
}
catch (OverflowException oe)
{
Console.WriteLine(oe.Message);
}
int result = a + b;
return result;
}
}
finally
- 应该把释放系统资源的语句写在 finally block 里面
有时候也在 finally block 里面写 log
class Program
{
static void Main(string[] args)
{
Calculator c = new Calculator();
Console.WriteLine(c.Add("abc","100"));
}
}
class Calculator
{
public int Add(string arg1,string arg2)
{
int a = 0;
int b = 0;
bool hasError = false;
try
{
a = int.Parse(arg1);
b = int.Parse(arg2);
}
catch(ArgumentNullException ane)
{
Console.WriteLine(ane.Message);
hasError = true;
}
catch(FormatException fe)
{
Console.WriteLine(fe.Message);
hasError = true;
}
catch (OverflowException oe)
{
Console.WriteLine(oe.Message);
hasError = true;
}
finally
{
if (hasError)
{
Console.WriteLine("Execution has error!");
}
else
{
Console.WriteLine("Done!");
}
}
int result = a + b;
return result;
}
}
throw
throw 将异常抛给调用者。
throw 关键字的语法比较灵活。
class Program
{
static void Main(string[] args)
{
Calculator c = new Calculator();
int r = 0;
try
{
r = c.Add("999999999999999999999", "100");
}
catch (OverflowException oe)
{
Console.WriteLine(oe.Message);
}
}
}
class Calculator
{
public int Add(string arg1,string arg2)
{
int a = 0;
int b = 0;
try
{
a = int.Parse(arg1);
b = int.Parse(arg2);
}
catch(ArgumentNullException ane)
{
Console.WriteLine(ane.Message);
}
catch(FormatException fe)
{
Console.WriteLine(fe.Message);
}
catch (OverflowException oe)
{
//Console.WriteLine(oe.Message);
throw oe;
}
int result = a + b;
return result;
}
}