Python Errors
Test Exceptions
Python, and most programming languages, may stop the execution of code and generate errors when problems occur. This in turn can create execution disruptions as well as unknown issues in some cases.
In Python, there are two main errors, syntax errors and exceptions.
- Syntax errors occur when there is a problem with the code’s syntax structure (e.g. missing characters or incorrect indentation)
- Exceptions errors occur when the program attempts to execute but detects an error (e.g. division by zero or undefined variables).
Handling errors can happen in two ways, built-in and custom-made.
Built-in errors
Built-in errors appear automatically, as part of the Python system, and they can be both syntax errors and exceptions.
# Syntax error missing quotation mark print("Hello, World!) # Output: SyntaxError: unterminated string literal (detected at line 2) # Exception undefined variable print(b) # Output: NameError: name 'b' is not defined
Custom-made refers to the development of error handling for a specific purpose. This can be anything that is expected to be a potential error or an existing built-in error, but with a custom error message by the developer. In Python, this can happen with the “try/except” statement.
Try/Except
“Try/except” statements allow developers to test code and handle errors. The “try” part tests the code, and “except” handles exceptions. Indentation and colon usage is important.
The following is a basic representation of the try and except.
try: print(b) except: print("Error! Something went wrong") # Output: "Error! Something went wrong"
The above example will raise the exception message with any error, as a specific exception has not been defined.
try: print(b) except NameError: print("Error! Undefined name") # Output: "Error! Undefined name"
The above example produces the built-in name error, but with a specific message from the developer.
try: print(b) except ZeroDivisionError: print("Error! Something went wrong") # Output: NameError: name 'b' is not defined
Although there is an exception with the message “Error! Something went wrong”, the program produces a name error. This is due to the built-in “NameError”, which deals with undefined variables.
In the example, try tests the code and except handles “ZeroDivisionError” (which deals with trying to divide by 0). But instead, the error is a name error, so the code executes and the program raises the built-in “NameError”.
There is no limit to the number of exceptions.
try: print(b) except ZeroDivisionError: print("Cannot divide by zero.") except TypeError: print("String can only concatenate with another string.") except ImportError: print("Cannot load the module.") except : print("Error! Something went wrong.") # Output: "Error! Something went wrong."
More information regarding built-in exceptions here.
Next: Python Basics Summary