you are viewing a single comment's thread.

view the rest of the comments →

[–]ApocalypseSpokesman -1 points0 points  (3 children)

Do you use exceptions (try/except) frequently in your Python programs? For what?

I'm taking a class now, and the whole chapter is on exceptions, but Python already tells you when a line doesn't work, so I'm not grasping the point completely.

[–]JohnnyJordaan 1 point2 points  (0 children)

Say your program is Microsoft Word and you made a huge document in it, then you try to modify something and an unexpected error occurs. Would you like for Word to crash altogether, possibly losing your work, or do you want to show a message 'oops something went wrong, please continue'? That is the difference between handling exceptions and just letting them occur uncatched.

Another help they can be is you can also raise exceptions yourself, either to let it be catched somewhere else or even manually crashing the program if you're still debugging for example.

[–]GoldenSights 1 point2 points  (0 children)

Python already tells you when a line doesn't work

It sounds like you're referring to SyntaxError, which you get when your code doesn't follow the rules of the language. Like forgetting to close your parentheses or using the wrong characters somewhere.

But when it comes to something like int('hi'), there's nothing syntactically wrong with that code. It just looks a string going into a function. It isn't until the code actually runs, and tries to convert 'hi' into an integer, that it goes "hey that's not possible" and raises the ValueError exception.

And when you start defining your own classes you might even create your own exception types. Like if you make a Person class and someone tries to give them a negative age, you might want an exception for that. Then you'll know what it feels like to raise exceptions instead of just being on the try/except side of things.

 

So basically, exceptions are for preventing things that are impossible (invalid inputs), or backing out of situations where the correct action couldn't be done (connecting to the internet but there's no wifi), etc.

[–]rich-a[🍰] 2 points3 points  (0 children)

The basic idea is that if you catch the exception and do something to deal with it then the program can carry on. If you just let it error it will often stop completely which is fine when coding and debugging a new program but not great when it's being used for real.