C
C#16mo ago
Pesar

❔ Exception Handling question

IF i Want to add exception handling to all of my program, do I have to put all of the code into the try{} block?
8 Replies
Messiah
Messiah16mo ago
I've always had that question as well. I think you can create a middleware to handle all exceptions, but I'm not entirely sure what kind of logic would start using this middleware
Hazel 🌊💃
Hazel 🌊💃16mo ago
Middleware only applies in certain environments Your entry point code can handle an exception at the root either prior to exit or restart Such as
MODiX
MODiX16mo ago
📅 do you remember?
REPL Result: Success
int runs = 0;
while (runs++ < 3) {
try {
Console.WriteLine("Doing cool things.");
throw new Exception("This is an example exception being thrown.");
} catch (Exception e) {
Console.WriteLine(e.Message);
}
}
int runs = 0;
while (runs++ < 3) {
try {
Console.WriteLine("Doing cool things.");
throw new Exception("This is an example exception being thrown.");
} catch (Exception e) {
Console.WriteLine(e.Message);
}
}
Console Output
Doing cool things.
This is an example exception being thrown.
Doing cool things.
This is an example exception being thrown.
Doing cool things.
This is an example exception being thrown.
Doing cool things.
This is an example exception being thrown.
Doing cool things.
This is an example exception being thrown.
Doing cool things.
This is an example exception being thrown.
Compile: 616.336ms | Execution: 90.183ms | React with ❌ to remove this embed.
ACiDCA7
ACiDCA716mo ago
it depends on the strategy how you want to deal with exceptions lets say you put one giant try catch around your program. what do you think will happen if an exception is thrown? spoiler: you will catch the exception and then the application closes (as long you dont program anything that restarts the app or so) there is middleware for stuff like aspnet but more generally there is unhandledexceptionhandler in the appdomain also just my 2 cents, try catches should in general only used where you have no full control like IO and exceptions can just happen. in all other cases your code should be improved so that you cant even get an exception, eg checking for null etc. bad code causes exceptions and should be treated as bugs also to expand.. try catches are there to get from an undefined state to defined state again by eg. rolling changes back or discard data. so the normal operation of the application can continue
Pesar
PesarOP16mo ago
I see Would it be better if I tried to prevent the said exception from happening, or like, work around it? For example if someone enters a number instead of a word, I check if it's a number and if it is, it reverts then back to the writing prompt?
Hazel 🌊💃
Hazel 🌊💃16mo ago
Preventing it from happening in the first place is better. Your example is great but wouldn't necessarily cause an exception, if we flip it around, it better demonstrates the concept:
string input = Console.ReadLine();

// validate first
if (!int.TryParse(input, out int suppliedInteger))
{
Console.WriteLine("The supplied input is not a valid integer.");
return;
}

...
string input = Console.ReadLine();

// validate first
if (!int.TryParse(input, out int suppliedInteger))
{
Console.WriteLine("The supplied input is not a valid integer.");
return;
}

...
Take a NullReferenceException which is easy to guard against but often neglected:
public class Sample {
public List<int> Integers { get; set; }
}

...
var sample = new Sample();

// this will throw a null reference exception because Integers is currently null
sample.Integers.Add(1);

// instead, verify before accessing and initialize if needed:
if (sample.Integers is null)
sample.Integers = new List<int>();

// this won't throw an exception because you ensured the property isn't null.
sample.Integers.Add(1);
public class Sample {
public List<int> Integers { get; set; }
}

...
var sample = new Sample();

// this will throw a null reference exception because Integers is currently null
sample.Integers.Add(1);

// instead, verify before accessing and initialize if needed:
if (sample.Integers is null)
sample.Integers = new List<int>();

// this won't throw an exception because you ensured the property isn't null.
sample.Integers.Add(1);
Hope this helps 🙂
Pesar
PesarOP16mo ago
Helps a ton, thank you all <:BL_PepeHeart:1142846257916809228>
Accord
Accord16mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?