Loading...

Python Try Except complete guide with examples

Python Try Except complete guide with examples

Whenever we are writing a program or pieces of code we follow specific program flow depending on our requirements however sometimes there can be certain cases that may occur in your way but at run time that you might not be able to handle and also may break or change your program flow. In such cases, we take the help of try/except statements of Python to help us take care of handling errors and sanity checking.

Introduction to try/except

So whenever we write a try keyword we intend that code to occur some error at run-time however Python lets the code run if there is no error so that when an error occurs then the code flows into the except block where we either handle the error or print the error message. They work similarly to try/except statements that you might have used in other programming languages such as C++, JavaScript, etc.

You can have multiple except clauses chained with your try block to take advantage of multiple exceptions which could be raised in run-time of different types.

Basic example

while True: try: inp = int(input("Enter a Number: ")) break except ValueError as e: print(e)
Code language: Python (python)

The example shown above describes the basic usage of try/except where I am trying to get input in integer form but there are chances that a user might enter a character literal or string resulting in the program crashing, so If such a case occurs it goes into except block and print the ValueError and since it’s wrapped inside a while loop it keeps doing that until the user inputs a correct value.

Understanding exceptions

You must be familiar with syntax errors, they occur whenever the interpreter parses the wrong syntax in the line of code that it’s scanning.

What if your code is syntactically correct yet it’s generating an error? Exactly, now you ran into an exception that was caused by run-time. That means the code you wrote was correct as per Python’s Parser requirements but it had some logical flaws or to say missed some exceptional case handling which then caused the program to crash whenever that particular or more exceptions were being raised.

Python comes with various built-in exception types such as ValueError which we used in the above example.

Some of the famous ones or widely used ones are

  • ZeroDivisionError – Occurs when you try to divide a number by zero
  • ValueError – Occurs when an incorrect value is assigned or if the value doesn’t exist
  • IOError – Related to Input Output operations such as working with files so if a file or directory you’re trying to access does not exist or goes corrupted or missing it would raise IOError.
  • EOFError – Occurs When the unexpected end of the file is met while reading input or files
  • TypeError – Occurs when the incorrect data type is used in some operation
  • KeyboardInterrupt – Occurs when a user tries to interrupt the program with control keys like CTRL + C
  • ImportError – Occurs when a module is failed to import into the script.

You can read more about Python’s built-in exceptions here.

How do we raise exceptions?

Now, you must be thinking what if I wanted to raise exceptions at some particular case or condition, well say no more Python has got a way for that as well.

We can use the raise keyword to forcefully raise an exception in Python so that for particular conditions we can stop the program wherever we wish with a custom error message.

Example

inp = input("Say My Name: ") if(inp != "Naman"): raise Exception("that's not my name")
Code language: Python (python)

Else with try/except

you can also use the else keyword with try/except although it only executes the code in the else part if the try block doesn’t raise any exceptions or has no errors.

Example

try: foo() except AssertionError as e: print("something went wrong!", e) else: bar()
Code language: PHP (php)

Here is the code in the else block will only get executed if the try block successfully calls and executes code in foo() otherwise, it will go into the except code block and display the error

Utilizing finally clause

Suppose that you had a scenario in which you would have to run a block of code no matter what happens in your program flow whether it’s raising exceptions or not regardless you’d like to continue the program execution, well in that case we have finally keyword which we use at the last of try/except or try/except/else clauses so that no matter what happens whether a try has generated errors or not, the code in finally block will always get executed.

Example

try: do_some_critical_task() except AssertionError as e: print("something went wrong!", e) else: proceed_the_flow() finally: execute_regardless()
Code language: Python (python)

Dirty usage of try/except/else/finally

I will show silly and an example of how dirty nested exception blocks can get and how it can lead you to write non-readable code with weird program flow patterns.

Example

def type_checker(val): counter = 0 for i in val: try: if i == "True": val[counter] = bool(True) if i == "False": val[counter] = bool(False) except: pass finally: try: flag = False y = 0 for x in i: if ord(x) >= ord('0') and ord(x) <= ord('9') and y == len(i): flag = True val[counter] = int(i) except: pass finally: try: if "." in i: try: val[counter] = float(i) except: pass except: pass counter += 1 return val arr = list() n = int(input("How many elements you want to add: ")) for i in range(n): tmp = input("Enter Any Value: ") arr.append(tmp) typed = type_checker(arr) print(typed)
Code language: PHP (php)

In the example above I am just trying to explicitly and manually convert the user-inputted values into a boolean, int, and float.

Of course, this is not how you should use try/except that’s why I am showing you a bad example of completely cluttered code.

Practicing with codedamn playgrounds

I would like to encourage all of you to try out playgrounds from codedamn which is free to use online IDE, you can use it to choose from multiple languages and build projects with people or do collaboration online without spending any hardware power or downloading anything.

You can try running the code snippets I’ve given before in the playgrounds and selecting Python 3 as the environment there.

Conclusion

  • try will execute your code as long as no run-time exceptions are occurring.
  • except will catch any exceptions or errors as soon as they are occurred and break the program flow
  • else will execute the code and continue the program flow if the try code block doesn’t produce any errors.
  • finally will execute the code consistently regardless of whatever happens in its preceding code blocks.

Sharing is caring

Did you like what NAMAN THANKI wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far