Middle
Milline on vahe throw ja throw ex kasutamisel C#-s?
sobes.tech AI
Vastus AI-lt
Kui kasutate throw ex, kaotate algse välja kutsumise virna, samas kui throw säilitab selle.
Näide:
using System;
public class Example
{
public static void MethodA()
{
try
{
MethodB();
}
catch (Exception ex)
{
Console.WriteLine("MethodA töötlemine:");
Console.WriteLine(ex.StackTrace);
throw ex; // kaotab teabe välja tekkimise koha kohta
}
}
public static void MethodB()
{
try
{
MethodC();
}
catch (Exception ex)
{
Console.WriteLine("MethodB töötlemine:");
Console.WriteLine(ex.StackTrace);
throw; // säilitab teabe välja tekkimise koha kohta
}
}
public static void MethodC()
{
throw new InvalidOperationException("Testväljapressimine");
}
public static void Main(string[] args)
{
Console.WriteLine("Näide `throw ex`-ga:");
try
{
MethodA();
}
catch (Exception ex)
{
Console.WriteLine("Mainis (`throw ex``-st):");
Console.WriteLine(ex.StackTrace);
}
Console.WriteLine("\nNäide `throw`-ga:");
try
{
MethodB();
}
catch (Exception ex)
{
Console.WriteLine("Mainis (`throw`-st):");
Console.WriteLine(ex.StackTrace);
}
}
}
Väljund näitab erinevusi kutsesilmus, näidates, et throw ex näitab kohta, kus tehti throw ex, samas kui throw näitab algset kohta, kus erand tekkis (MethodC).
Tabelis saab esitada peamised erinevused:
| Omadus | throw ex |
throw |
|---|---|---|
| Kutsesilmu | Asendatakse praeguse kutsesilmu vastu | Säilitatakse (algne kutsesilm) |
| Tekkimise koht | Näitab kohta, kus tehti throw ex |
Näitab algset kohta, kus erand tekkis |
| Kasutus | Peamiselt — erindi tüübi muutmiseks või teabe lisamiseks (kuigi see ei ole parim praktika) | Korduvaks erindi taaskäivitamiseks |