Catching specific exception

Hi All, I want to catch the specific exception and throw if any other exceptions occur, this is in c#, in general, how do we handle it? any resource link will help too. Thanks
4 Replies
Jochem
Jochem2y ago
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch You can have multiple catch blocks, and the type annotation will determine whether that block runs for any given exception. Exception blocks should go from most to least specific, and only one will run. This will catch ArgumentNullException, and any other types will be rethrown with the trace intact:
try
{
string s = null;
ProcessString(s);
}
// Most specific:
catch (ArgumentNullException e)
{
Console.WriteLine("{0} First exception caught.", e);
}
// Least specific:
catch (Exception e)
{
throw;
}
try
{
string s = null;
ProcessString(s);
}
// Most specific:
catch (ArgumentNullException e)
{
Console.WriteLine("{0} First exception caught.", e);
}
// Least specific:
catch (Exception e)
{
throw;
}
SureshPasham
SureshPashamOP2y ago
Hi Jochem, I need to look for this Exception: " Order has been modified outside this session" in my case,if so have some code to handle. if not I will throw an execution.
Jochem
Jochem2y ago
That will have an exception type that you can catch like I described. Alternatively you could examine the exception
try
{
//code that throws exceptions
}
catch (Exception e)
{
if (e.Message == "Order has been modified outside this session")
{
//your code here
}
else
{
throw;
}
}
try
{
//code that throws exceptions
}
catch (Exception e)
{
if (e.Message == "Order has been modified outside this session")
{
//your code here
}
else
{
throw;
}
}
I'd consider that a bit of a last resort though, you shouldn't generally try matching on values intended for human consumption, because someone might decide to change it upstream with no warning. Try to figure out the type of the exception that's getting thrown, the documentation for the library you're using should have that information.
SureshPasham
SureshPashamOP2y ago
Okay...
Want results from more Discord servers?
Add your server