17 May Errors and Exceptions in Python
In today’s article, we’d be discussing errors and exceptions in Python. Errors refers to problems which can occur in a program and stop the program’s execution. We can have the error in form of a “traceback” error message which provides a full report on it.
While Exceptions are raised when some inside events occur that change the flow of the program. In handling this errors and exceptions, we use the Error Handling method to do this.
Let’s look at each of the different types of errors we have in Python. This errors can be classified into two classes;
- Syntax errors
- Logical errors (Exceptions)
Syntax Errors
Syntax error are errors caused by not following the proper structure or syntax of the language. This can also be called parsing error.
An example of what the syntax error looks like can be seen below;
1 if b == 1 2 print("hello")
Output
In this example, we can observe a colon :
is missing at the end of the if statement.
1 File "<ipython-input-2-d2c0dbe9a7d6>", line 1 2 if b == 1 3 ^ 4 SyntaxError: invalid syntax
Now, let’s move further to what Logical Errors looks like.
Logical Errors(Exceptions)
Logical errors are errors that occurs at runtime. These type of errors are also known as exceptions. An example of this error types are; FileNotFoundError
, ZeroDivisionError
, ImportError
Also whenever this error occurs, it creates an exception object whereby if they aren’t handled properly ,it returns a full report traceback to that particular error.
Let’s look at some few examples below;
1 # initialize the variable 2 myvalue= 50 3 4 # we perform division with 0 5 result= myvalue / 0 6 print(result)
Output
When we ran this code it gave us a ZeroDivision type of Error
1--------------------------------------------------------------------------- 2 ZeroDivisionError Traceback (most recent call last) 3 <ipython-input-3-4303a2aa4bd8> in <module> 4 3 5 4 # we perform division with 0 6 ----> 5 result= myvalue / 0 7 6 print(result) 8 9 ZeroDivisionError: division by zero
Let’s try the FileNotFound
Error Example. This means we’ll try opening a document that doesn’t exist in our working directory.
1open("file.txt")
Output
After, running the code, it gave us this FileNotFoundError
error which we have below;
1--------------------------------------------------------------------------- 2 FileNotFoundError Traceback (most recent call last) 3 <ipython-input-4-93b2af11911f> in <module> 4 ----> 1 open("file.txt") 5 6 FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'
Python Built-in Exceptions
Python contains different built-in Exceptions. We can view all this built-in exceptions using the built-in local()
function as seen below:
1 print(dir(locals()['__builtins__']))
Whenever we run the code, it prints out all the built-in exceptions for us. Few of these errors are shown below along with their causes.
Let’s move further and see how we can handle all these errors in our code
Error Handling
Handling Exceptions with Try/Except/Finally
The Try/Except/Finally is a very efficient way of handling exceptions. The try
block is usually used for generating exceptions while the Except block helps us in handling the error and finally block executes the code, regardless of the result of the try- and except blocks.
An example of this is shown below;
1 try: 2 print("hello") 3 4 # unsafe code to run 5 print(50 / 0) 6 7 except: 8 print("an error occurs") 9 10 finally: 11 print("I'm back here")
This is what we generated after running the code;
1 hello 2 an error occurs 3 I'm back here
Handling Many Exceptions With Try & Except
We can also define as many exception blocks as we want, let’s say we want to handle a special kind of error;
Let’s see the example below;
Output
We should have this result after running the code;
1 Variable a is not defined
1 try: 2 print(a) 3 except NameError: 4 print("Variable a is not defined") 5 except: 6 print("Something else went wrong")
That’s about errors and exceptions in Python. Let’s have your observations and questions in the comment box below. Thanks for reading.
No Comments