טיפול בשגיאות ב-C#

לכידת שגיאות מסייעת לשמירה על התוכנית רצה.

בתוכנית הבאה, התוכנית מצפה לקבל מספר כקלט, ולהמיר אותו על ידי הפונקציה convert ל-int. במקרה שהקלט שיגיע לא יהיה ניתן להמרה למספר, תתקבל שגיאה והתוכנית תעוף.

static void Main(string[] args) {
    Console.WriteLine("Enter a number: ");
    int num = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine(num);
    Console.ReadLine();
}

Try…catch

בשימוש Try…catch התוכנית מנסה לעשות משהו, ואם היא לא מצליחה, הוא נותנת למתכנת שליטה על מה שיקרה. תפיסה כללית של Exception תתפוס כל שגיאה שתגיע. עכשיו אם תהיה שגיאה, התוכנית לא תעוף אלא תבצע מה שיש בתוך החלק של ה-catch.

static void Main(string[] args) {
    try {
        Console.WriteLine("Enter a number: ");
        int num = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine(num);
    }
    catch (Exception) {
        Console.WriteLine("Error");
    }
            
    Console.ReadLine();
}

אפשר לטפל בשגיאות ספציופיות לפני שתופסים שגיאה כללית.

static void Main(string[] args) {
    try {
        Console.WriteLine("Enter a number: ");
        int num = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine(num);
    }
    catch (FormatException) {
        Console.WriteLine("Enter only numbers");
    }
    catch (OverflowException) {
        Console.WriteLine("The number is too big");
    }
    catch (Exception) {
        Console.WriteLine("Error");
    }
            
    Console.ReadLine();
}

Printing error messages

לבלוק ה-catch מועבר לנו הפרמטר Exception. אפשר להשתמש בו כדי לקבל את השגיאה שהגיעה אליו. למשל, אם בתוכנית שבדוגמא אני אכניס תו במקום מספר, תתקבל ההודעה: Error: Input string was not in a correct format.

static void Main(string[] args) {
    try {
        Console.WriteLine("Enter a number: ");
        int num = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine(num);
    }
    catch (Exception ex) {
        Console.WriteLine($"Error: {ex.Message}");
    }
            
    Console.ReadLine();
}

ניווט במאמר

מאמרים אחרונים

Weekly Tutorial