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

4734
JohnnyJordaan•

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

def divide(dividend, divisor):
    if divisor == 0:
        print('division by zero undefined!')
        return   # what should it return???
    return dividend / divisor

Because when the caller doesn't check the return value, it doesn't detect the None being returned (or whatever you choose to return)

# this will just store None in the dict as if it's somehow 'ok'
my_dict[result] = divide(1/0) 

Instead you would like to have the function raise an exception to notify the user that it's actually breaking

if divisor == 0:
    raise ValueError('division by zero not undefined!')

As then the store in my_dict will 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 do

sum_of_all_values = sum(my_dict.values())

which 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'.

25
Earhacker•

Excellent answer, but there's a typo:

'division by zero not undefined!'

In the first and third code blocks.

3
JohnnyJordaan•

Right, thanks.

1
RandQuotesOP•

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 raise just report the error?

3
JohnnyJordaan•

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

def get_name_from_user():
    inp = input('please enter your name')
    return inp

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

if not inp.isalpha():
    raise ValueError('illegal character in name')
return inp

Then the caller of that function can do

try:
    user['name'] = get_name_from_user()
    big_storage.save(user)
except ValueError as e:
    print('didnt save user because {}'.format(e))

So you need to create the exception in order to catch it. raise does exactly that.

Btw

and then handle it silently?

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...

10
RandQuotesOP•

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?

6
JohnnyJordaan•

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 reraise to both save a message in some log and crash the program.

7
fukitol-•

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.

1
thisusernameismeta•

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.

1
-Tiff-•

Exceptions shouldn't happen in the first place, so either there's a bug in the program or something else went wrong

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.

try:
    return json.load(contents)
except json.JSONDecodeError
    return lxml.html.parse(contents)

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.

2
JohnnyJordaan•

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.

2
markusmeskanenMahi•

raise is 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:

 character = Character()
 character.set_level(40)

Now, level is just an integer, there's no issue for Python if you do character.set_level(130), but for your game's rules that's an error. So you might wanna put that inside of your method:

def set_level(self, value):
    if 0 <= value <= 100:
        self._level = value
    else:
        raise ValueError('Character level must be in the 0-100 range!')

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:

As then the store in my_dict will 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 do

sum_of_all_values = sum(my_dict.values())

Think about it yourself, what would happen in that scenario if we didn't return an error in the divide() function?

3
RandQuotesOP•

That makes sense. I'm going to have to play around with it some more, but I think I get the idea now.

1
tunisia3507•

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 open function 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 from open back 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 FileNotFoundError is raised.

1
nog642nog642•

If someone is trying to divide by 0, it might be better to raise ZeroDivisionError instead of ValueError.

1
JohnnyJordaan•

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.

2
ManyInterestsfrom fridge import beer•

There's a lot of reasons you may want to raise an exception. Usually this would be because you know some fatal or unexpected bad thing may happen if you don't. You may also raise an exception with a specific message to provide better information to a user. This is particularly important when designing interfaces that other people will use.

In many other languages, 'look before you leap' is a philosophy for dealing with potentially error-prone operations. In Python 'easier to ask forgiveness than permission' is more often used than in some other languages. Exceptions are what make that philosophy work well. Many libraries even make their own exception classes to raise in particular cases to be more informative. This aides users in exception handling and understanding why exceptions happen.

Also consider that, at some level, you are able to handle exceptions because somebody before you decided to raise an exception.

5
ka-splam•

I can see the purpose behind exception handling, but I can't see how "raise" would be useful.

That's like "I can see the purpose behind reading books, but I can't see how 'writing' is useful". Exceptions have to come from somewhere before they get handled. raise is where they come from.

It's how your code says "a problem happened", without having to write your own "I'll return xyz which you care about, and a status code which tells you if there was an error, and you'll have to test that all the time to look for errors".

Instead the Exception system runs through the entire language like an elevator, and you can raise Exception messages where you find problems, and it will raise them up to the appropriate level - wherever the nearest try/catch is. One level out, three levels out.

2
RandQuotesOP•

Maybe I'm misunderstanding how raising an exception works, but doesn't raising an exception just print out what the error was? Wouldn't handling silently usually be better?

1
ka-splam•

Python is a factory, your code is a machine in the factory, and the user is a big boss far away.

Machine breaks, raises an exception, technician working near it looks at it. Now the code has stopped running and the exception handler process builtin to the company is kicking in.

Oh no it looks serious. They stop what they're doing and run to get the floor manager. That's the function stopping completely and going back to the place it was called from.

floor manager looks and decides this needs the site manager. They stop what they're doing, this function breaks and goes back to where it was called from.

The site manager gets there, can't do anything, and now the production line is grinding to a halt. As a last ditch "help", the site manager calls the big boss and says "machine is broken" (prints the message), and the big boss is annoyed.

This is raising an exception with no try/catch anywhere.

With try/catch it runs differently.

Machine breaks, raises an exception, technician working near it looks at it. Now the code has stopped running and the exception handler process builtin to the company is kicking in.

catch: if there's something wedged in it, the technician pokes the backward forward button a bit to free it up. Catch: if the waste bucket is full on one side it can falsely trigger an alarm, they shake it. If the problem is neither of these, they stop what they're doing and run to get the floor manager. That's the function stopping completely and going back to the place it was called from.

floor manager looks. Catch: if it's a problem with the power supply that happened once or twice, and the technician has never seen it, they fix the plug and reset it. Catch: if it's a reboot with an override code the technician doesn't know, they do it. If it's not these problems, they catch anyway, write in the factory process log books, then raise the same exception again and decide this needs the site manager, function breaks and goes back to where it was called from.

The site manager gets there. Catch: if they can spend money to get someone there to fix it, the site manager can authorise it, but they need to log it. If they need to block the production run to move some big things out of the way, the site manager can authorise it, but they need to log that it happened. If the site is literally on fire there's not much they can do - the site manager calls the big boss and says "machine is on fire, calling the fire brigade" (prints the message), and the big boss is annoyed.

So the raise happens where the problem is, but the exception mechanism runs right through the language, deep into all the function calls and back out again, looking for places which declare "I can catch and handle this kind of exception". Some handling is retrying, some is printing a log message and then re-reporting the problem. Some exceptions have nobody who can deal and the only thing that can happen then, once it's gone all the way up, is that everything stops and someone hears about it.

And the machine doesn't have to know any of this, it just raises an exception, and the rest of the system brings it to the attention of whatever can handle it, if anything.

Wouldn't handling silently usually be better?

How would you know there was a problem? "You're ill? I'll tape your mouth shut and tie you up in a locked room. If we don't know about it, you're not really ill, eh?"

2
RandQuotesOP•

Ok, I think I get it. I was essentially misunderstanding what raise actually did.

4
roelschroeven•

If a function can handle an error or other exceptional situation itself, it probably should do so and then everything as well. But most of the time, that's not possible. For example: a function that should read from a file can't read that file, since it was passed an incorrect file name. There's nothing that function can do to remedy that situation; the only thing it can do, is inform its caller of the situation.

There are different approaches to do that.

A function that detects an error, could for example return an error code to its caller. That approach is widely used in e.g. in C. There are some problems with that approach:

  • In some situations, it's not possible to distinguish between an error code and a valid return code. For example, the C function atoi (which converts a string to an integer) returns 0 if the string doesn't contain a number, but 0 is also the current return value if the string is "0".
  • Each function needs to check the return codes from the functions it calls, because otherwise the error is silently ignored. In many cases, that function doesn't know what to do either, and just passes the return code up the chain.

Python (and other languages) uses exception handling. Exceptions can never be confused with valid return values since they are a completely different mechanism. You can raise them where you detect an error condition, and catch them at the place where you can best handle them (inform the user about it, if nothing else). The functions in the call hierarchy between the one that raises an exception and the one that catches it, don't need to be sprinkled with return value checks since exceptions are automatically propagated upwards until they are caught.

So, why would you raise an exception? To inform calling code about an error (or other exceptional situation), and allow for it to be handled at the most suited level in the call hierarchy.

2
destiny_functional•

Because an error occurred in your code and you want to handle what the program does when that happens.

If you write a function and it gets input it can't deal with you should raise an Exception for instance.

1
Karl_Marx_•

I'll give you a simple explanation. Let's say you ask your user to put a number down, but you have the input set as an integer.

Your user types "one."

Your program crashes.

Now to stop this you can throw a type exception to say something like "please use integers only."

You can throw a blanket to catch everything, or use individual exceptions, I believe it's proper to use specific exceptions.

1
muwaahid•

I read this as "raising expectations" and was like "idk if this is the right sub for existential crises..."

1
cyberpunking•

It seems like you're wondering why you would ever raise an exception instead of just handling it locally.

Lets say you have a StringHandler object that has a method StringHandler.handle(string).

If string is badly formatted, that's an error that you need to deal with somehow. Perhaps you can show the user an error message, or you can attempt to fix the formatting internally. Without using exceptions, you would have to decide how to deal with this issue inside of the handle() method, and you have to decide what the right way to deal with this error is there and then.

But what if you have two different StringHandler objects in different places, or even in different programs. In one place it makes sense to do one thing with a badly formatted string, and in another place it makes sense to do another.

With exceptions, you can raise StringFormatException inside of the handle() method, without deciding what the correct thing to do with the bad string is, and later on you can do something like:

try: StringHandler.handle(string)
except StringFormatException:
    #print or reformat or whatever you need to do based on the context that this is being called in
1
RandQuotesOP•

That's exactly what I was wondering. Thanks.

1