Python Try...Except

What is exception in Python

In Python, exceptions are the errors that occur during the execution of a program for various reasons like invalid user input, file not found, network issues, or errors in the code.

Exceptions should be handled properly, otherwise they can terminate the program abruptly.

What is try...except in Python

In Python, 'try' and 'except' blocks are used to handle the exceptions or errors that occur during the execution of a program.

Using 'try' and 'except' blocks, you can catch exceptions and handle them gracefully, allowing the program to continue running or perform some cleanup before exiting.

Try block contains the code that you want to execute.

Except block contains the code that runs if an exception of the specified type occurs. It is usually used to give message to the users about the exception and run the program smoothly.

Simple syntax of 'try' and 'except' blocks

The basic syntax of 'try' and 'except' blocks in Python is as follows:

Explanation of code
  • try:: The 'try' keyword defines the try block. This block contains the code that you want to execute.
  • Code to be executed but that may raise an exception: This will be replaced by the actual code which is to be executed. If this code raises any exception, it will be handled by the except block.
  • except SomeException as e:: This defines the except block with SomeException. 'SomeException' will be replaced by the name of actual exception.
  • # Code that runs if the exception raised: This will be replaced by the actual code that runs if the exception is raised.

Example of 'try' and 'except' blocks

Here is an example of using 'try' and 'except' blocks in Python to handle a division by zero error:

Output of the above example
An error occurred: division by zero
                                
Explanation of code
  • try:: The 'try' keyword defines the try block.
  • result = 15 / 0: This is the code block under try block. Here, 15 cannot be divided by 0 (zero) and it will raise an exception named ZeroDivisionError.
  • except ZeroDivisionError as e:: This defines the except block with exception named 'ZeroDivisionError'. This captures the exception instance in the variable 'e'.
  • print(f"An error occurred: {e}"): This prints a message with the error defined in 'e'.

Try...except with else block

The 'else' block can be used along with 'try...except' to execute code that should run only if no exceptions were raised in the try block.

In other words, if the 'try' block runs smoothly, the 'else' block will also run.

Example of 'else' block
Output of the above example
The result is 5.0.
                                

Exception is the base class for all built-in exceptions except for SystemExit, KeyboardInterrupt, and GeneratorExit. It can be used to catch any exception that is not caught by more specific exception handlers.

Explanation of code
  • try:: The 'try' keyword defines the try block.
  • result = 10 / 2: This is the code block under 'try' block. Here, 10 is divided by 2 and the result is passed to the variable 'result'. The code will be executed and it will not raise any exception.
  • except Exception as e:: This defines the 'except' block with exception named 'Exception'. This captures the exception instance in the variable 'e'.
  • else:: The 'else' keyword defines the else block. The code under this block will be executed if the 'try' block does not raise any exception. In the example, the code 'print(f"The result is {result}.")' under this block will be executed.

In the above example, since the code in the 'try' block does not raise any exception, the code in the 'else' block is executed and it prints the result.

Try...except with finally block

The 'finally' block can be used along with 'try...except' to ensure that certain code always runs, regardless of whether an exception occurred.

The finally block is typically used for cleanup actions such as closing a file or closing a database connection or releasing resources.

The 'finally' block is optional.

Example of 'finally' block
Output of the above example
The result is 5.0.
The resources are cleaned.
                                
Explanation of code
  • finally:: The 'finally:' keyword defines the finally block.
  • print("The resources are cleaned."): This prints a message. But this code will be replaced by your clean up or other code.

It is important to learn try except blocks in Python to handle exceptions and errors gracefully. It allows your program to run smoothly and provides a better user experience.

Common Exceptions in Python

Here are some common exceptions in Python:

  • ZeroDivisionError: Raised when you try to divide a number by zero.
  • FileNotFoundError: Raised when you try to open a file that does not exist.
  • ValueError: Raised when a function receives an argument of the right type but an inappropriate value.
  • TypeError: Raised when an operation or function is applied to an object of inappropriate type.
  • IndexError: Raised when you try to access an index that is out of range in a list or other sequence.
  • KeyError: Raised when you try to access a key that does not exist in a dictionary.
  • NameError: Raised when you try to use a variable that has not been defined.
  • AttributeError: Raised when you try to access an attribute that does not exist for an object.
  • ImportError: Raised when an import statement fails to find the module definition or when a from ... import fails to find a name that is to be imported.
  • SyntaxError: Raised when the parser encounters a syntax error.
  • IndentationError: Raised when there is an indentation error in the code.
  • MemoryError: Raised when an operation runs out of memory.
  • OverflowError: Raised when the result of an arithmetic operation is too large to be represented.
  • RecursionError: Raised when the maximum recursion depth is exceeded.
  • StopIteration: Raised by the next() function to indicate that there are no further items produced by the iterator.
  • KeyboardInterrupt: Raised when the user hits the interrupt key (normally Control-C or Delete).
  • SystemExit: Raised by the sys.exit() function to exit from Python.
  • RuntimeError: Raised when an error is detected that doesn't fall in any of the other categories. The associated value is a string indicating what precisely went wrong.

Python Compiler For Live Practice

Practice the above Python code in the following Python Editor. Create more Python try...except examples in the following Python code editor and click Execute button to check the output. Output will be displayed in Python Code Output section.

Python logo Python Editor
Python Code Output