我正在尝试理解System.Exception
类,但在覆盖功能方面遇到了一些问题。我尝试拦截异常DivideByZero
并写入我在派生类的函数中生成的用户消息System.Exception
。这是我的代码:
public class zeroDivision
{
public void Deleter()
{
double z; int i = 0;
try
{
z = 10 / i;
Console.WriteLine("N={0} i={1} Result={2}", 10, i, z);
}
catch (zeroMessage e) **<====problem here: DivideByZeroException**
{
Console.WriteLine("N={0} i={1} Result={2}", 10, i, e.Message);
}
}
}
public class zeroMessage : System.Exception <--here debugger even doesn't come
{
public override string Message
{
get
{
string msg = base.Message;
msg = "Деление на ноль ЗАПРЕЩЕНО!!!";
return msg;
}
}
}
class Program
{
static void Main(string[] args)
{
zeroDivision zero = new zeroDivision();
zero.Deleter();
Console.Read();
}
}
当我调用:catch(zeroMessage e) - 它未处理,但如果我调用:catch(Exception e) - 它有效。我的错在哪里?我不明白
-------------------------------------------
在论坛高手的一些帮助下,我用工作功能重新制作了这个任务。也许它对任何人都有用:
public class zeroDivision
{
public void Deleter() //First way
{
double z; int i = 0;
try
{
z = 10 / i;
Console.WriteLine("N={0} i={1} Result={2}", 10, i, z);
}
catch (DivideByZeroException)
{
Console.WriteLine("N={0} i={1} Result={2}", 10, i, "Делить на ноль НИЗЗЯ!!!");
}
}
public double Deleter2(int a, int b) //Second way
{
if (b == 0) throw new zeroMessage();
return a / b;
}
public void prn(int i, int j) //Third way
{
try
{
Console.WriteLine(Deleter2(i, j));
}
catch (zeroMessage z)
{
Console.WriteLine(z.Message);
}
}
public void firstDeleter() //Updated Yesterday's code - Forth way
{
double z; int i = 0;
try
{
if (i == 0) throw new zeroMessage(); //!!!
z = 10 / i;
Console.WriteLine("N={0} i={1} Result={2}", 10, i, z);
}
catch (zeroMessage e)
{
Console.WriteLine("N={0} i={1} Result={2}", 10, i, e.Message);
}
}
}
public class zeroMessage : System.Exception
{
public override string Message
{
get
{
string msg = base.Message;
msg = "Деление на ноль ЗАПРЕЩЕНО!!!";
return msg;
}
}
}
class Program
{
static void Main(string[] args)
{
zeroDivision zero = new zeroDivision();
zero.Deleter();
try
{
double result = zero.Deleter2(10, 0);
Console.WriteLine(result);
}
catch (zeroMessage z)
{
Console.WriteLine(z.Message);
}
zeroDivision zero1 = new zeroDivision();
zero1.prn(10, 0);
zeroDivision zero2 = new zeroDivision();
zero2.firstDeleter();
Console.Read();
}
}