Errors and Exceptions in Python

Learn about errors and exceptions in Python and how to handle them effectively in your programs.

10 min read
Beginner

Syntax errors

Syntax errors are errors caused by the use of incorrect Python syntax.

The following example shows an example of a syntax error where the print function was written without any round brackets.

python
print 'Hello, World!'

You can see that whenever a syntax error occurs in Python, the parser points at the point where the error has occurred using an upright triangle (^) symbol.

The right way to solve syntax errors is by writing the correct syntax in Python.

Exceptions or Logical errors in Python

Even if a statement or expression is syntactically correct, it may throw out an error during execution. Such errors are termed as logical errors or exceptions.

These errors occur as a result of not correctly writing the logic of the program. The following example shows an exception being raised when a number is divided by zero:

python
print(10/0)

As you can see, the parser shows us that there is an exception called ZeroDivisionError.

Handling exceptions in Python

Now that we know what exceptions are, let us learn how to handle them.

Python provides a set of statements that can be used to handle exceptions and they are known as try-except statements. They are similar to try-catch blocks used in other programming languages such as C, C++, and Java.

The syntax for try-except statements is as follows:

try:
    # Code to be executed by default
except:
    # Code to be executed if try block fails to be executed

The try-except statement consists of two parts: Try and Except. It works as follows:

  • The try part of the statement consists of a set of code to be executed.
  • If no exception occurs, the code in the try statement block is executed and the except clause is skipped.
  • If an exception occurs in any part of the code in the try statement, the rest of the code is skipped and the except statement block is executed.

Here is an example of a try-except statement where we pass a string as an input to the program but the required input is an integer:

python
try:
  num = 10 / 0 
  print("Try block executed.")
except Exception as e:
  print("Oops! There was an exception:", e)

We can also specify the type of exception we want to catch using the except statement. Here is an example where the exception is specified as ValueError and we are passing the string as an input to the program like before:

python
try:
  num = 10 / 0
except ZeroDivisionError:
  print("Oops! There was a ZeroDivisionError exception")

Also, if you want to execute something at the end of the try-except statements, then, you can use the try-except-finally statement. The syntax of a try-except-finally statement is as follows:

try:
    # Code to be executed by default
except:
    # Code to be executed if try block fails to be executed
finally:
    # Code to be executed after the try-except block

Here is an example showcasing the use of the try-except-finally statement where we are passing a string as before:

python
try:
  num = 10 / 0
except ZeroDivisionError:
  print("Oops! There was a ZeroDivisionError exception")
finally:
  print("The try except block finished executing.")

How to raise exceptions in Python?

Sometimes you might want to raise exceptions by yourself when a program is executing for easier debugging.

You can do so by using the raise keyword followed by the type of exception in Python. Here is an example where we are passing a negative number as an input to the program below which requires a positive number:

python
try:
  x = -2
  if x < 0:
    # Using raise keyword to raise ValueError
    raise ValueError("Number is negative")
  else:
    print("The number is positive.")
except ValueError as e:
  print("The exception is", e)

Test your knowledge

🧠 Knowledge Check
1 / 15

What is a syntax error in Python?