C# İstisna Yönetimi
Try ve Caatch kullanılmadan yazılan prograda oluşan hata programı tamamen durdururken, İstisna eklenmiş program çalışmaya devam eder.
// Block of code to try
}
catch (Exception e){
// Block of code to handle errors
}
Örnek:
namespace Projeler {
class Program {
static void Main(string[] args) {
int x, y;
Console.Write("1. Sayıyı Giriniz: ");
x = Convert.ToInt16(Console.ReadLine());
Console.Write("2. Sayıyı Giriniz: ");
y = Convert.ToInt16(Console.ReadLine());
try {
Console.WriteLine("{0} / {1} = {2}", x, y, x / y);
}
catch (Exception e) {
//Console.WriteLine("Hata Oluştu : {0}", e);
Console.WriteLine("Sanırım işlemde mantık hatası yaptınız. :(");
}
finally { //Hata olsada olmasada calisacak bolum
Console.WriteLine("İyi Günler");
}
Console.ReadKey();
}
}
}
namespace Projeler
{
class Program
{
static void Main(string[] args)
{
byte x;
try {
Console.Write("0-255 Arasında Bir Sayıyı Giriniz: ");
x = Convert.ToByte(Console.ReadLine());
Console.WriteLine("Doğru Değer Girdiniz");
}
catch (Exception e) {
Console.WriteLine("Olmadı... 0-255 arası bir sayı girmediniz. :(");
//Console.WriteLine("Hata Oluştu : {0}", e);
}
finally {
Console.WriteLine("İyi Günler");
}
Console.ReadKey();
}
}
}
Örnek
class degiskenler {
static void Main() {
try {
int a;
Console.Write("Bir sayı girin: ");
a=Convert.ToInt16(Console.ReadLine());
}
catch(Exception e) {
Console.WriteLine("nBir hata yaptınız..");
}
finally {
Console.WriteLine("nUygulamayı kullandığınız için teşekkürler");
}
}
}
Try Catch Trow Finally Uygulaması
class degiskenler {
static void Main() {
try {
int a;
Console.Write("Bir ile Beş arasında bir sayı girin: ");
a=Convert.ToInt16(Console.ReadLine());
if(a<0 || a>5) {
throw new ArithmeticException("Bir ile Beş arasında girmediniz.");
}
}
catch(Exception e) {
Console.WriteLine("nBir hata yaptınız..");
}
finally {
Console.WriteLine("nUygulamayı kullandığınız için teşekkürler");
}
}
}
using System;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string[] fatih = new string[7];
int fatih2 = 0;
private void button1_Click(object sender, EventArgs e)
{
try
{
fatih[fatih2] = textBox1.Text; fatih2++;
}
catch (Exception)
{
MessageBox.Show("Maksimum Dizin " + fatih2.ToString() + " olduğu için daha fazla giremezsiniz.");
MessageBox.Show("Dizinler : " + string.Join(",", fatih));
}
}
private void button2_Click(object sender, EventArgs e)
{
}
}
}