ELI5: What is the purpose of raising exceptions?
Bit of background: I used to do some programming when I was in middle school and high school, with basic, visual basic, and c++. But then I went to college and ended up stopping. So, I haven't really done any coding in like 15 to 20 years. I ended up looking for a program that apparently doesn't exists, so recently, I decided to retake up coding to make it for myself. So I started using SoloLearn, and I just learned about handling and raising exceptions.
I can see the purpose behind exception handling, but I can't see how "raise" would be useful. Could anyone enlighten me as to why you would raise an exception?
Posted Dec 16, 2017, 10:44 AM UTC · edited
Exceptions are raised when an exceptional situation occurs, eg something the program doesn't want to happen. In case the programmer itself determines a situation to be 'exceptional', eg incorrect user input, unexpected calculation result, basically anything out of the ordinary it can raise an exception to stop the flow. The big difference between just 'checking' if it's ok, like doing
Because when the caller doesn't check the return value, it doesn't detect the None being returned (or whatever you choose to return)
Instead you would like to have the function raise an exception to notify the user that it's actually breaking
As then the store in
my_dictwill not happen as the exception occurs before it being saved. Of course Python has a built-in ZeroDivisionError for this, but you get the idea why stuff like this should raise exceptions and not 'work' until you dowhich raises an exception because the None value stored can't be part of a sum.
So it shouldn't matter if it's Python or the programmer who raises the exception, what matters is that they are raised when something happens that shouldn't keep 'working'.
Excellent answer, but there's a typo:
In the first and third code blocks.
Right, thanks.
I think I might be misunderstanding what raising does, but wouldn't best practice be to catch the exception, and then handle it silently? Doesn't
raisejust report the error?The point is that Python only raises exceptions that it 'sees' as exceptional. If you make a program that gets user input in a function
and you want it to break when the user enters anything that's not in the alphabet, you can't catch this as an exception as it isn't raised in the first place. You could do
Then the caller of that function can do
So you need to create the exception in order to catch it.
raisedoes exactly that.Btw
Silence is dangerous. Imho it should always notify a user or a sysadmin (maybe by logging) to show that something exceptional has happened. Exceptions shouldn't happen in the first place, so either there's a bug in the program or something else went wrong, but silencing is not the way to go there unless you want to discover that your system has no recovery backups since last year because its backup creation exception was handled silently...
I think I get it. So, basically, it to create your own error messages when something that you don't want to happen happens? Then you use it to inform the end user of this error?
Message is just a medium, it isn't the whole story. The essence of an exception is that the flow of the program is stopped. See that
big_storage.save()call above? That statement is not executed when the exception is raised, so not only could it print a message, you actively prevent it from executing further statements by interrupting flow.Exceptions are an emergency brake, the message to the user is just an implementation of what happens next. You can also write scripts that just crash when an exception happens (so without any try/except block), like those you run automatically by a system scheduler. Then the scheduler will get a non-zero returncode (used by programs to indicate failure) and could notify you of the task being failed. Or you can also use
reraiseto both save a message in some log and crash the program.Or handle it in your code. You can reprompt the user for different input, retry a database connection handle, try writing a file again in a different location, etc.
Okay, so I think the thing for you to think about here is that big projects are big, they have lots of layers, libraries, frameworks, etc all included in them.
If the only one 'experiencing' your code was the end user, then you would be right, you should deal with exceptions, not just toss them down the line for someone else to deal with.
The piece that I think youre missing here is that this someone else in a lot of cases wont be the end user. A lot of code you write will be used more by other coders than directly by the person running this final application. In a complex project with lots of moving pieces, a lot of time, the piece of code that detects that something went wrong wont necessarily be the appropriate place to deal with the fact that something went wrong. You want to think about things like cohesion and coupling and a these other fun things while you write. You dont want to litter 'dealing with exceptional situations' all over your code. Neither would you want to hide that someone is doing something with your library that it isnt meant to do.
A lot of the time when youre writing an exception, your audience isnt someone using your application, its someone using uour code to write their own application. Or its just targetted to another area in your application.
The folks who wrote python's sum could have dealt with Nones in the array by just adding 0, but they decided that you (writer of code, user of libraries) would probably want to know that youre missing a value and probably something is wrong.
So youre right, if by 'end user' you mean any other place that is using your code, not necesarily a user of your application.
Sorry if this whole rant seems common sense to you, it actually tookme awhile to realize thr target audience of my code was other software developpers, not software users.
Disagree in the context of Python. In some cases, exceptions are not particularly "exceptional" and used as part of the EAFP coding approach. It is fine to silently handle things if you can/if it is appropriate.
Simplified example if expecting either JSON content or content that should be parsed with LXML if it isn't valid JSON.
My point is you can leverage exceptions to do things like this rather than messily coding a bunch of conditionals to check first before you attempt to do things (or LBYL.)
I think it's important for new Python users to also see this approach and recognize that it isn't frowned upon when using Python, and is even encouraged in many cases.
Frankly, to me just assuming contents is xml if it fails to decode as json is also gambling and dangerous. Perhaps the content is json but there's a syntax error or the contents are neither of those formats.
I agree with your point that exceptions aren't wrong to use to simply handle flow instead for calling for an emergency, but I'm very weary of 'fix-by-assumption' cases, which is exactly what you're showing. Of course in a certain environment you could safely say that it's guaranteed that contents is either of those formats and it isn't expected to contain syntax errors, but still as that being an exception, it isn't a good programming teaching example. Many famous computer errors (Therac, Ariane crash) are partly based on in-code assumptions.
raiseis used when you want to "create" your own error when something happens in your program that isn't technically an error, but you want it to be. Say you're making a game where your character can be anything from level 0 to level 100:Now,
levelis just an integer, there's no issue for Python if you docharacter.set_level(130), but for your game's rules that's an error. So you might wanna put that inside of your method:Now if someone's using your library, they will get a proper error, and it's up to them to decide how to handle it.
Edit: Also, I would really put emphasization on this part of u/JohnnyJordaan's reply:
Think about it yourself, what would happen in that scenario if we didn't return an error in the
divide()function?That makes sense. I'm going to have to play around with it some more, but I think I get the idea now.
Functions call functions, which call functions. It's usually not the same developer controlling all the code all the way down to the bare metal - you're almost certainly using libraries written by other people (including the python standard library!). If you want to open a file, but the file doesn't exist, there are lots of different ways of handling that, and the file API writer doesn't necessarily know which one you want. The best they can do is say "You've asked me to open a file, but it doesn't exist; now what?". Sometimes the direct caller of the
openfunction knows what to do in that situation. But sometimes it doesn't - maybe that function is only supposed to be called if you know the file exists. So it makes sense to refer the error fromopenback up the chain to the caller's caller, and so on, until something knows what to do in the case that the file doesn't exist. If nobody knows what to do if the file doesn't exist, the program should halt.You may note that this is exactly what happens when a
FileNotFoundErroris raised.If someone is trying to divide by 0, it might be better to raise
ZeroDivisionErrorinstead ofValueError.That would be the default case of course, but my point was to show the way to form a general exception based on an invalid value. ZeroDivisonError isn't a subclass of ValueError. So if you would define your implementation to raise a ValueError for whatever value you don't seem fit to handle (for example either argument not being a number) then the user of your implementation doesn't have to handle ZeroDivisionError specifically, it can just catch ValueError.