Exception Handling
!"#!"$%&%'()*+,-./012+*'
(30)042*2-
5#+6#72089#:%!(;"+6#72!)%<=)>/0
+?'$*)+@A$B+6#7!2*4%7,
C)DE";A00%&'+6+@F1@A!
!%&.2=C2)A0)"2A+G"
H2%&*+,
I
H?J2*+,/0*0<(KL2#M7@(0%(K#A+,2*'""
32
C42%&?"3"(K/4*4N?4%&?N?"3"(K
/8C5O3*.P0@+G"(KL#M2*11
O"J*2-*+,4%4*'3)2*+,/0
)BQ0%;
32R
J@S0&2
J$/J'Q0@S02
J%;?'A02
J%;32%?A0
T@S0&
2
TJ@%4M0M)0((5?(UR
VA(85F0((2W)N0((2*%4M0<4 )4M0((A
VA(8VA(5F#7)2*+,(0602AQ08C5O#:F
V0%XYZ5A0%1@Q0V0%*BA=
VA(8[05F#7)2*+,*LP0\)-S0
]1@0A
#7
]#[((5FA!*4)$%&*+,/A!
^#A_5F0`
a05F%&**L#2
b#XXcd05F+,)e(;Q000Af(=
Cdc5F04%&,
[C5F*;(;A
b0#0(5F/)%&,
[5F0(;%N
)1Q0@
5W)
gT%h(iFjdT#D*4J! JZ(S0&*BA*Q2
^00hb^0AiF!,) %Af0#!$*LP0 *L1A
gd(hiF-0Q02
b5h5iF42A*+,/M$1%;0?S0*<*;+,
23*2-%;0
]((0h(iF&2
Vh(iF$S#: *;+,A0
V0%O0h(iF#k+GSN(0%
O0Vh]#0(iF*;+,&+GSA02
C/2@M%?0
Z
public class Humans
{
public int Age
{
get { return Age; }
set
{
if (value >= 0)
{
Age = value;
Console.WriteLine(“Tuoi la {0}”, Age);
}
else throw new Exception(“Tuoi khong chinh xac”);
}
}
}
H1*;+,A0*;+,A?'
/*2#N?@M%?0Z)
*+,/0J*;+,S0&2
I2@%;
Al0
static void Main(string[] args)
{
Console.WriteLine(“Simple Exception Example”);
Humans a = new Humans() { Age = 30; }
try
{
for (int i = 0; i < 4; i++)
a.Age -= 10;
}
catch (Exception e)
{
Console.WriteLine(“Exception Message: {0}”, e.Message);
}
}
m'I20(3#:%;Al08H;
A#7*'S0*2?%n/02
8H;0(KI2*'3
I2@%;
Al0
o#:$0WQ00;pBMqr;srJrrlJr"A0(Q0+GS[
(K/0J28V0*?%;0(KI2A0"&)
Kết quả:
Tuoi la 30
Tuoi la 20
Tuoi la 10
Tuoi la 0
Exception Message: Tuoi khong chinh xac
m'I20(3#:%;Al08H;
A#7*'S0*2?%n/02
8H;0(KI2*'3
I2@%;
0
while (true)
{
try
{
Console.Write(“Nhap 1 so tu 1 den 10, nhap rong de thoat: ”);
string input = Console.ReadLine();
if (input == “”) break;
int index = Convert.ToInt32(input);
if (index < 1 || index > 10)
throw new IndexOutOfRangeException(“Ban da nhap so ” + input);
Console.WriteLine(“So ban nhap la {0}”, index);
}
catch(IndexOutOfRangeException e)
{
Console.WriteLine(“Co loi! Ban phai nhap so tu 1 den 10! {0}”, e.Message);
}
catch(Exception e)
{
Console.WriteLine(“Co loi! {0}”, e.Message);
}
}
I2@%;
0
Khi chạy:
Nhap 1 so tu 1 den 10, nhap rong de thoat: 5
So ban nhap la 5
Nhap 1 so tu 1 den 10, nhap rong de thoat: 20
Co loi! Ban phai nhap so tu 1 den 10! Ban da nhap so 20
Nhap 1 so tu 1 den 10, nhap rong de thoat: abc
Co loi! Input string was not in a correct format.
Nhap 1 so tu 1 den 10, nhap rong de thoat:
H;0%&?0
(;
H;0%&?0(;(KI*+,N2A0Q0t2%&*+,4R
%&*+,R89#:uuN4*?'*+,/0+J240N*2-
Auu?(KI*+,)2%&#DM0((VA(85
catch
{
Console.WriteLine(“Co loi nao do xay ra”);
}
H;v0A
C%0B<J#7? %&A0289#:F%0\Jv0
)$v*?#7? %&A02"0D*?v2
]1)A4*+0!*?v%;A%;08OA$)AA0(<7
R%;v0A*'<0)A
9#:%;
Al0lv0A
string path = @"c:\users\public\test.txt";
var file = new System.IO.StreamReader(path);
char[] buffer = new char[10];
try
{
file.ReadBlock(buffer, index, buffer.Length);
}
catch (System.IO.IOException e)
{
Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message);
}
finally
{
if (file != null)
{
file.Close();
}
}