9 topshiriq Xatolikni Qo'llash


Download 39.51 Kb.
bet2/3
Sana20.11.2023
Hajmi39.51 Kb.
#1789255
1   2   3
Bog'liq
algoritm 9 topshiriq javob

Dastur O'zini Qo'llash: Dasturda bir xato yuzaga kelsa, dastur yozuvini log fayliga yozing. Log fayli topilmagan yoki yozib bo'lmay qolsa, dastur to'xtasin va xatolik haqida ma'lumot chiqarsin. (Exception va boshqa obyektlar orqali).

using System;
using System.IO;

class Program


{
static void Main()
{
try
{
Console.WriteLine("Fayl nomini kiriting:");
string fileName = Console.ReadLine();

// Fayl nomi bilan log faylini yaratamiz


string logFileName = "log.txt";
using (StreamWriter logWriter = new StreamWriter(logFileName, true))
{
logWriter.WriteLine($"Dastur ishga tushdi: {DateTime.Now}");

// Faylni o'qish uchun FileStream yaratamiz


using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
{
// Faylni o'qish uchun StreamReader yaratamiz
using (StreamReader reader = new StreamReader(fileStream))
{
// Fayl ichidagi matnni o'qib konsolga chiqaramiz
string content = reader.ReadToEnd();
Console.WriteLine("Fayl matni:\n" + content);
}
}
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"Xato: {ex.Message}");
LogError(ex);
}
catch (IOException ex)
{
Console.WriteLine($"IOException xato: {ex.Message}");
LogError(ex);
}
catch (Exception ex)
{
Console.WriteLine($"Umumiy xato: {ex.Message}");
LogError(ex);
}
finally
{
Console.WriteLine("Finally blok ishga tushdi.");
}
}

static void LogError(Exception ex)


{
// Log fayliga xatoni yozamiz
using (StreamWriter logWriter = new StreamWriter("log.txt", true))
{
logWriter.WriteLine($"Xato: {ex.Message}");
logWriter.WriteLine($"Stack Trace: {ex.StackTrace}");
logWriter.WriteLine("----------------------------------------");
}
}
}

  1. Fayl yozish: Dastur yozing, foydalanuvchi tomonidan kiritilgan matnni bir faylga yozsin. Agar fayl topilmagan yoki yozib bo'lmay qolsa, dastur to'xtasin va xatolik haqida ma'lumot chiqarsin. (IOException va boshqa obyektlar orqali).

using System;
using System.IO;

class Program


{
static void Main()
{
try
{
Console.WriteLine("Fayl nomini kiriting:");
string fileName = Console.ReadLine();

Console.WriteLine("Matnni kiriting:");


string content = Console.ReadLine();

// Fayl nomi bilan StreamWriter yaratamiz


using (StreamWriter writer = new StreamWriter(fileName, true))
{
// Matnni faylga yozamiz
writer.WriteLine(content);
Console.WriteLine("Matn faylga muvaffaqiyatli yozildi.");
}
}
catch (IOException ex)
{
Console.WriteLine($"IOException xato: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Umumiy xato: {ex.Message}");
}
finally
{
Console.WriteLine("Finally blok ishga tushdi.");
}
}
}


  1. Download 39.51 Kb.

    Do'stlaringiz bilan baham:
1   2   3




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling