Dasturlash tillari va axborot-kommunikatsiya texnologiyalari 1-semestr
322
Car myCar =
new
Car(
"Rusty"
, 90);
try
{
// Trigger an argument out of range exception.
myCar.Accelerate(-10);
}
catch
(Exception e)
{
// Process all other exceptions?
Console.WriteLine(e.Message);
}
catch
(CarIsDeadException e)
{
Console.WriteLine(e.Message);
}
catch
(ArgumentOutOfRangeException e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
Bu istisnolarni qayta ishlash mantig‘i kompilyatsiya bosqichida xatolikka olib
keladi.
Muammo shundaki, birinchi
catch bloki
System.Exception xatoligidan
tashqari barcha istisnolarni
qayta ishlay oladi,
CarlsDeadException va
ArgumentOutOfRangeException larni ham. Oxirgi 2ta
catch bloki imkonsizdir.
Bitta empirik qoidani yodda saqlang: catch bloklarini shunday joylashtirish
kerakki, birinchi
catch eng maxsus istisnolarni, oxirgi
catch esa umumiyroq
istisnolarni qayta ishlashi kerak.
Shunday qilib, agar ixtiyoriy istisnolarni qayta ishlaydigan
catch blokini
aniqlaydigan bo‘lsak, u quyidagicha aniqlanadi:
// This code compiles just fine.
static
void
Main(
string
[] args)
{
Console.WriteLine(
"***** Handling Multiple Exceptions
*****\n"
);
Dasturlash tillari va axborot-kommunikatsiya texnologiyalari 1-semestr
323
Car myCar =
new
Car(
"Rusty"
, 90);
try
{
// Trigger an argument out of range exception.
myCar.Accelerate(-10);
}
catch
(CarIsDeadException e)
{
Console.WriteLine(e.Message);
}
catch
(ArgumentOutOfRangeException e)
{
Console.WriteLine(e.Message);
}
// This will
catch any other exception
// beyond CarIsDeadException or
// ArgumentOutOfRangeException.
catch
(Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
// A generic catch.
static
void
Main(
string
[] args)
{
Console.WriteLine(
"***** Handling Multiple Exceptions
*****\n"
);
Car myCar =
new
Car(
"Rusty"
, 90);
try
{
myCar.Accelerate(90);
}
catch
{
Console.WriteLine(
"Something bad happened..."
);
}
Console.ReadLine();
Dasturlash tillari va axborot-kommunikatsiya texnologiyalari 1-semestr
324
}