Home > Enterprise >  Does it matter which type of exception you use in Python?
Does it matter which type of exception you use in Python?

Time:02-28

I'm new to working with exceptions in Python. Wondering how much it matters that you get the type of exception -- i.e. ValueError, FileNotFoundError, TypeError, etc. -- correct. For example:

files = os.listdir(path)
if not files:
    msg = "directory is empty"
    raise ValueError(msg)

Obviously this is not a ValueError. But an error will be raised and the message will be displayed. So, does it matter (functionally) which error type I use? Or is it primarily to inform the user what went wrong?

CodePudding user response:

It's important for being able to selectively handle exceptions correctly. You'll want to have a look at the builtin exception hierarchy. You can see that different exception types inherent from each other, and thus allow you to be specific in which errors you expect and want to handle explicitly, and which you don't:

except Exception:

This handles all exceptions (that you should handle except for ones that you shouldn't).

except OSError:

This handles all errors coming from interactions with the OS.

except FileNotFoundError:

This very specifically handles the case where files aren't found, but not for example PermissionError, which is a separate error within the OSError hierarchy.

You should only handle exceptions when you have a plan what to do with them, and otherwise let them bubble up to either be handled by a higher caller, or let the program terminate if there's an unhandleable error that your program can't do anything about.

Using that hierarchy properly, and defining your own exceptions in a proper hierarchy, makes error handling much easier and your code more maintainable in the long run.

CodePudding user response:

In some applications, depending on the situation, your code will not fail, but it will not perform the operation you want, because there may be a user behavior or workflow situation that does not reconcile with the code you have written. In this case, you might want to create your own exception to manipulate the workflow or user behavior the way you want.

To do this, you can create your own exception using the raise keyword and the Exception() function.

For example, let's say you are coding a number guessing game and your application is trying to guess the number the user has in mind. If you don't set a limit on the user, it may take a very long time for your application to guess the number it keeps because there is an infinite option. Let's say we ask the user to keep a number between 0 and 100;

num=int(input("Please enter a number between 0 and 100: "))

if num not in range(0,101):

raise Exception("You must enter number between 0 and 100!")
  • Related