Python for .NET Developers Transcripts
Chapter: The Python Language
Lecture: C# error handling

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Let's look at a program that's not very reliable so it's going to need some error handling. Here we have our run method for the Errors class
0:09 and what it's going to do is it's going to generate a bunch of numbers 1 to 20 and it's going to add, I don't know
0:16 some Fibonacci numbers or something like that on the end. And then it's going to try for each one of those numbers to call SketchyMethod.
0:24 The name might give you a hint of what's happening here. So it's going to set the color to gray so you can see what's going on really well
0:31 and then it's going to set it to yellow and if there's an error based on the error it's going to say cyan and then some kind of message.
0:39 So here's error handling in C# we'll call a function and a try block. And then we can distinguish between the different types of errors
0:46 by having different catch blocks. So there's a SocketException. We have catch(SocketException). There's a ValidationException
0:53 like some value is not valid we'll get it down here. If it's some unknown Exception we can just catch it in general and to find a variable
1:01 which will not appear and we're going to print out oh, there's some kind of error we're going to get the type
1:07 say it's this type of error and here's the message We were not really planning on this but something bad happened
1:12 Pretty cool, let's run it and see how that works There you go, you can see we didn't have a lot of faith in it so we run it, and it says
1:21 calling it with 1, hey that worked, 2 that worked we call it a 6, for some reason, we got an overflow or underflow arithmetic exception, right?
1:29 This was one that got caught down here we didn't expect it, so we just printed out the type in a message Down here, we've got a network error
1:39 that was a socket exception that was thrown We said there's something wrong with your connection It worked for a while, network, and then arithmetic
1:45 and then lets see In this one, we pass it 0 and it said no, no, no, I can't work with 0 that's not something I can compute with
1:54 Okay, so here's error handling in C# couple things to note, try, do stuff, catch But the catch has to be most specific down to general
2:05 Because the way it works is the error's thrown and C# says, does it derive from SocketException? If yes, we go here. Otherwise, does it derive
2:13 from ValidationException. Otherwise, does it derive from Exception Finally, yes everything derives from Exception that can be thrown, so down here
2:20 we are handling this So, you've got to make sure that you have it more specific to more general the way it goes down here, all right
2:27 This is our super reliable way of working with this SketchyMethod

Talk Python's Mastodon Michael Kennedy's Mastodon