今日休假的最後一天,在寢室coding,想起java的項目有些糾結,就把C#的課本拿出來溫習一下。練習的是兩段異常處理的程序。
異常處理的方法一:可以在函數中處理異常並拋出,看下實例,最常見的除數爲零的例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 異常2
{
class ThrowExample
{
public void Div()
{
try
{
int x = 5;
int y = 0;
int z = x / y;
Console.WriteLine(z);
}
catch (DivideByZeroException e)
{
throw new ArithmeticException("被除數爲零");
}
}
public static void Main(string[] args)
{
try
{
ThrowExample te = new ThrowExample();
te.Div();
}
catch (Exception e)
{
Console.WriteLine("Exception:{0}", e.Message);
}
Console.ReadKey();
}
}
}
這個實例是將異常處理放在div函數中,在mian函數中直接接收異常的處理。
方法二:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 異常
{
class ThrowExample
{
public void Div()
{
try
{
int x = 5;
int y = 0;
int z = x / y;
Console.WriteLine(z);
}
catch (DivideByZeroException)
{
throw;
}
}
public static void Main(string[] args)
{
try
{
ThrowExample te = new ThrowExample();
te.Div();
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception:{0}", e.Message);
}
Console.Read();
}
}
}
這個是把異常在div函數中拋出,然後再在主函數中處理異常,兩種方法均可實現異常的處理。