Error and Exception Handling in Python: Fundamentals for Data Scientists | by Erdem Isbilen | Towards Data Science

There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.
Syntax errors are similar to grammar or spelling errors in a Language. If there is such an error in your code, Python cannot start to execute your code. You get a clear error message stating what is wrong and what needs to be fixed. Therefore, it is the easiest error type you can fix.
Missing symbols (such as comma, bracket, colon), misspelling a keyword, having incorrect indentation are common syntax errors in Python.
Exceptions may occur in syntactically correct code blocks at run time. When Python cannot execute the requested action, it terminates the code and raises an error message.
Trying to read from a file which does not exist, performing operations with incompatible types of variables, dividing a number by zero are common exceptions that raise an error in Python.
We must eliminate the syntax errors to run our Python code, while exceptions can be handled at runtime.
Logical errors are the most difficult errors to fix as they don’t crash your code and you don’t get any error message.
If you have logical errors, your code does not run as you expected.
Using incorrect variable names, code that is not reflecting the algorithm logic properly, making mistakes on boolean operators will result in logical errors.
# Syntax Error-1: Misusing the Assignment Operatorlen("data") = 4Output:  File "ErrorsAndExceptions.py", line 1    len("data") = 4SyntaxError: can't assign to function call# Syntax Error-2: Python Keyword Misusefr k in range(10):    print(k)Output:  File "ErrorsAndExceptions.py", line 4    fr k in range(10):       ^SyntaxError: invalid syntax# Exception-1: ZeroDivisionErrorprint (5/0)Output:Traceback (most recent call last):  File "ErrorsAndExceptions.py", line 12, in <module>    print (5/0)ZeroDivisionError: integer division or modulo by zero# Exception-2: TypeErrorprint ('4' + 4)Output:Traceback (most recent call last):  File "ErrorsAndExceptions.py", line 10, in <module>    print ('4' + 4)TypeError: cannot concatenate 'str' and 'int' objects
When your code has a syntax error, Python stops and raises an error by providing the location of the error in your code and a clear error definition.
# Syntax Error-1: Misusing the Assignment Operatorlen("data") = 4Output:  File "ErrorsAndExceptions.py", line 1    len("data") = 4SyntaxError: can't assign to function call
You need to correct the syntax error to run your code.
len("data") == 4Output:True
The main aim of the exception handling is to prevent potential failures and uncontrolled stops.
We can catch and handle an exception with a try-except block:
try block contains the code to be monitored for the exceptions.
except block contains what to be done if a specific exception occurs. If no exception occurs then this section is skipped and the try-except statement is concluded.
If exception raised matches with the one specified in except keyword, the code inside the except block is executed to handle the exception.
You can catch any exception if you do not specify any type of exception in the except keyword.
try block execution is terminated when the first exception occurs.
try-except block may have more than one except block to handle several different types of exceptions.
Optional else block is executed only if there is no exception occurs in a try block. If any exception is raised, the else block will not be executed.
Optional finally block is used for clean up code. This block is always executed.
try: #code to monitor print (5/0)#this code will not be executed #as above line raises a ZeroDivisionError print ("this code will not be executed")except ZeroDivisionError as e: #code to handle the exception when it occurs print(e) print("OPPS")else: print("try block executed if there is no error")finally: print("finally block is always executed")Output:integer division or modulo by zeroOPPSfinally block is always executed
If a specific condition occurs, you can manually raise exceptions with a raise keyword.
student_age = -4if student_age < 2: raise Exception("Sorry, student age cannot be lower than 2")Output:Traceback (most recent call last):  File "ErrorsAndExceptions.py", line 49, in <module>    raise Exception("Sorry, student age cannot be lower than 2")Exception: Sorry, student age cannot be lower than 2
We can define our own exception types if we would like to have more control over what will happen in specific conditions.
To do this, we inherit from the Exception class.
class InvalidStudentAgeException(Exception):"""Exception for errors in the student age  Attributes:  student_age -- student_age that we monitor  error_message -- explanation of the error """def __init__(self, student_age, error_message="Student age should  be in 2-10 range"):self.student_age = student_age self.error_message = error_message super().__init__(self.error_message)student_age = int(input("Enter Student age: "))if not 1 < student_age < 11: raise InvalidStudentAgeException(student_age)Output:Enter Student age: 54Traceback (most recent call last):  File "ErrorsAndExceptions.py", line 68, in <module>    raise InvalidStudentAgeException(student_age)__main__.InvalidStudentAgeException: Student age should be in 2-10 range: 54 is not a valid age
Above, we override the constructor of the Exception base class to use our own custom arguments student_age and error_message. With using super().__init__(self.error_message), we instantiate the base class, Exception, argument which help us to display the error message.
We must eliminate the syntax errors to run our Python code, while exceptions can be handled at runtime.
We can catch and handle an exception with a try-except block.
We can define our own exception types if we would like to have more control over what will happen in specific conditions.
In this post, I explained the basics of error and exception handling in Python.
The code in this post is available in my GitHub repository.
I hope you found this post useful.
Thank you for reading!