DEV Community

elifrie
elifrie

Posted on

Raising Exception Explained

Hey everyone! I'm back with another beginner's explanation, but this time in a new language.

For the past few weeks I've been sinking my teeth into python and learning the basic motions. Working through errors is something that every software engineer of every level has to deal with. In order to continue to run your program regardless of certain errors coming up it is important to 'Raise Exceptions'.

Raising an exception allows you to set a default response if your program runs into some type of error. This way your entire program won't crash due to a small syntax error and based on your error message you may be able to tell where your program ran into an error.

Now let's see an example.

Let's say you are writing a plethora of if statements to handle many conditions and situations. Your program is crashing but you're not sure where you're running into issues. Is it when you're checking if variable x is a string? Is it when you're making sure that the price is between set parameters? By raising an exception for each condition you can specify what message to return in the event of failure. Then handling errors without breaking code is much more simple.

if isinstance(x, str):
   print("X is a string!")
else:
   raise Exception("Please enter a valid string!")

##Input: 2
  Output: Please enter a valid string!

if 1 <= price <= 100
   print("The price is right!")
else:
   raise Exception("Please enter a number between 1 and 100")

##Input: 2
  Output: The price is right!
Enter fullscreen mode Exit fullscreen mode

Without raising an exception the program would break on the user, but now it will return an error to guide them in the correct direction and provide information to guard against future errors.

Top comments (0)