文章目录
C# 异常捕获
捕获异常
csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Test
{
int result;
Test()
{
result = 0;
}
public void division(int num1,int num2)
{
try
{
result = num1 / num2;
}
catch(DivideByZeroException e)
{
Console.WriteLine("Exception caught:{0}", e);
}
finally
{
Console.WriteLine("Result:{0}", result);
}
}
static void Main(string[] args)
{
Test t = new Test();
t.division(23, 0);
Console.ReadKey();
}
}
}
运行效果
自定义异常
csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
public class TempIsZeroException : ApplicationException
{
public TempIsZeroException(string message) : base(message)
{
}
}
public class Temperatrue
{
int temperature = 0;
public void show()
{
if (temperature == 0)
{
throw (new TempIsZeroException("ZERO TEMPERATRUE FOUND"));
}
else
{
Console.WriteLine("Temperatrue:{0}", temperature);
}
}
}
class Test
{
int result;
Test()
{
result = 0;
}
public void division(int num1,int num2)
{
try
{
result = num1 / num2;
}
catch(DivideByZeroException e)
{
Console.WriteLine("Exception caught:{0}", e);
}
finally
{
Console.WriteLine("Result:{0}", result);
}
}
static void Main(string[] args)
{
Temperatrue t = new Temperatrue();
try
{
t.show();
}
catch (TempIsZeroException e)
{
Console.WriteLine("TempIsZeroException:{0}", e.Message);
}
Console.ReadLine();
}
}
}
运行结果
抛出异常
csharp
catch(Exception e)
{
...
Throw e
}