Code phân biệt sự khác nhau giữa try-catch và Tryparse trong C#
vd: Nhập vào 1 số, kiểm tra nếu là chữ thì cho nhập lại. Sử dụng try-catch và Trypasre để kiểm tra ngoại lệ
public static int NhapSo(char n){
int x = 0;
Console.WriteLine("Nhập số " + n);
////////Dùng Try-catch
//while (true){
// try{
// x = int.Parse(Console.ReadLine());
// break;
// }
// catch (Exception){
// Console.WriteLine("Nhập sai kiểu, nhập lại số " + n);
// }
// //finally { Console.WriteLine("Kết thúc Try_Catch"); }
//}
//return x;
//////// Dùng TryParse
while (true){
String y = Console.ReadLine();
if (int.TryParse(y, out x) == true){
break;
}
else
Console.WriteLine("Nhập sai kiểu, nhập lại số " + n);
}
return x;
}