βœ… Exception handling

I'm trying to understand exceptions but i'm having a hard time. So when an error occurs in my program. For example :
int number = Console.Readline();
Console.Writeline($"{number}");
int number = Console.Readline();
Console.Writeline($"{number}");
If the input here in this case wasn't an integer but a string. The program would crash right? And to prevent it from crashing we use exception handling with try and catch ?
13 Replies
Merineth πŸ‡ΈπŸ‡ͺ
Or do exception handling even prevent the program from crashing in the first place?
Kiel
Kielβ€’3w ago
This line here:
int number = Console.Readline();
int number = Console.Readline();
Would be invalid, and would cause the program to fail to compile - ignoring the missing capital L in ReadLine - error CS0029: Cannot implicitly convert type 'string' to 'int' However, what would cause an exception to be thrown would be, for example:
int number = int.Parse(Console.ReadLine());
int number = int.Parse(Console.ReadLine());
If the input was not an integer For this very simple example, it's recommend to use int.TryParse instead of catching an exception, because that's the point of the TryParse method Example:
if (!int.TryParse(Console.ReadLine(), out var number))
{
// do something, such as printing a friendly error
// or replace the if with a while to loop until input is valid
}
else
{
// past this point, number is confirmed to be a valid int
}
if (!int.TryParse(Console.ReadLine(), out var number))
{
// do something, such as printing a friendly error
// or replace the if with a while to loop until input is valid
}
else
{
// past this point, number is confirmed to be a valid int
}
Depending on how new to C# you are, that might be a lot of information at once, sorry, but it is important information to learn
Merineth πŸ‡ΈπŸ‡ͺ
Ok, for simple parsing I'll start using TryParse But what about exceptions? What if i tried to divide two IntΒ΄s and encounter a DividebyZero error? What is the main purpose of exception handling? To prevent it from crashing ?
Kiel
Kielβ€’3w ago
Exception handling is meant to, kinda as the name would imply, handle "exceptional" circumstances such as dividing by zero. In general it's a bad experience for you or a user you're writing a program for to experience a crash. So the goal of exception handling is to "gracefully" handle something bad happening and instead of crashing, you can display an error message, or continue on normally as if nothing happend, or whatever the situation calls for in your case, a DivideByZeroException would be thrown, and if you wanted to tell the user there was a problem instead of just...crashing/closing immediately, you would want to try { } catch (DivideByZeroException ex) { } and handle the exception appropriately
Merineth πŸ‡ΈπŸ‡ͺ
So i would use the Try on a block of code which i want to attempt. And the catch(crash reason) is used to determine what we want to do in case the crash reason happens?
Kiel
Kielβ€’3w ago
the "catch" block is for catching either any exception, or a specific exception I'll include three example below
try
{
// your exception is thrown here
}
catch (SomeException ex) // Handle when a SPECIFIC exception is thrown
{ }
catch (Exception ex) // Handle with ANY exception is thrown
{ }
catch // Handle ANY exception and ignore - this is generally not a good practice unless you have a good reason
{ }
try
{
// your exception is thrown here
}
catch (SomeException ex) // Handle when a SPECIFIC exception is thrown
{ }
catch (Exception ex) // Handle with ANY exception is thrown
{ }
catch // Handle ANY exception and ignore - this is generally not a good practice unless you have a good reason
{ }
And you can, for example, combine the above (except the last one I think) to handle different exceptions....differently
Merineth πŸ‡ΈπŸ‡ͺ
what does the exmean?
Kiel
Kielβ€’3w ago
it's the name of the exception variable - you can access properties on ex to view different data that might be important for the base Exception class the only really useful thing might be ex.Message You can name the variable whatever you like, most people I see name it ex or just e, or if you don't need to use the variable, you can omit it entirely like I do below
try
{
var input = Console.ReadLine();
var number = int.Parse(input);
var division = 5 / number;
}
catch (NullReferenceException)
{
// input was null!
}
catch (FormatException)
{
// number failed to parse (int.Parse failed)
}
catch (DivideByZeroException)
{
// input was 0
}
try
{
var input = Console.ReadLine();
var number = int.Parse(input);
var division = 5 / number;
}
catch (NullReferenceException)
{
// input was null!
}
catch (FormatException)
{
// number failed to parse (int.Parse failed)
}
catch (DivideByZeroException)
{
// input was 0
}
Ignoring the fact I'm using int.Parse instead of int.TryParse, here's an example of handling multiple exceptions in different ways
Merineth πŸ‡ΈπŸ‡ͺ
So the throw new exceptionname uses my own custom exception?
Kiel
Kielβ€’3w ago
Correct, you can throw an exception at any time if you so choose You can make your own exception class, or you can throw any of the base exceptions (even just new Exception(...) too)
Merineth πŸ‡ΈπŸ‡ͺ
Nice. So if i catch a DivideByZeroException, inside the catch block i can do Throw my own exception?
Kiel
Kielβ€’3w ago
There's nothing stopping you from throwing your own exception in a catch block, but generally you should have a good reason for doing so. A proper real-world usecase could be if you have your own generic ErrorException type which wraps other exceptions so you can display more detailed information than a plain old DivideByZeroException can keep in mind that in a catch block, thrown exceptions are not caught - you would need ANOTHER try { } catch { } block inside it lol
Merineth πŸ‡ΈπŸ‡ͺ
Okay! that makes sense c: thanks!
Want results from more Discord servers?
Add your server