Error Handling in Python

Error Handling in Python

·

5 min read

Error handling refers to the anticipation, detection, and resolution of programming, application, and communications errors. Specialized programs, called error handlers, are available for some applications. The best programs of this type forestall errors if possible, recover from them when they occur without terminating the application, or (if all else fails) gracefully terminate an affected application and save the error information to a log file.

Types of Errors

Syntax 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.

HOW TO FIX :

  • You need to correct the syntax error to run your code.
def summ(a,b):
    c = a+b
    returm c

print(summ(2,4))

The error message below is the output;

  File "syn.py", line 3    
    returm c
           ^
SyntaxError: invalid syntax

Exceptions

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.

# The code below was used to parse to various webpages where some of the pages returned an error. 

def scrape():
  tot = []
  seed(5) # seed random number generator

  for _ in range(500): # generate some integers
    val = randint(6000, 8662)

    try:
      tot.append(parse_fields(get_url(val)))
    except IndexError:
      continue #Required for the null Indent values and the None value entries in the parse function
  tot

  return tot

HOW TO FIX :

  • 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.

Logical errors

  • 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.
def summ(a,b):
    c = a+b
    return a

print(summ(2,4))
2

We have returned the variable a instead of c which doesn't return an error but gives the wrong output.

HOW TO FIX : Read through the code thoroughly

Notes

  • A try clause is executed up until the point where the first exception is encountered.
  • Inside the except clause or the exception handler, you determine how the program responds to the exception.
  • You can anticipate multiple exceptions and differentiate how the program should respond to them.
  • Avoid using bare except clauses.

Tip

Fail quickly and cleanly with accurate and thorough diagnostic details

#datascience #errorhandling #python #error #tryexcept