Python Exception-Handling

My github repository for the functions I learned as part of the course. Here's what this notebook covers:

https://github.com/Akina-Aoki/IBM-Data-Science-Files/blob/main/Exception%20Handling.ipynb

Understanding Exceptions

An exception is a problem that stops a program. Programmers use exception handlers to deal with these problems and keep the program running smoothly. It's like having a backup plan for when things go wrong.

To deal with exceptions, programmers use something called an exception handler. This is like a safety net that catches exceptions and tells the program what to do next. For example, it might display an error message to the user or try a different approach to keep the program running smoothly.


Errors vs. Exceptions

Errors come from a computer or a system and causes the program to completely stop running.

Exceptions are problems in the code that can be fixed and controlled.


How exception- handling works

try-except statement

The try-except statement is used to handle errors in Python code. First, the code in the try block is attempted. If an error occurs, Python looks for a matching exception in the except block and executes the corresponding code.

For instance, if a program tries to open a file but fails, it jumps to the except block with the IOError. Sometimes, other errors occur that aren't caught by the IOError, so additional except blocks are added. However, it's not recommended to catch all errors without specifying the type.

An else statement can be used to show that the program ran successfully. Finally, it's important to close files using the finally statement, regardless of whether an error occurred or not.


Common Exceptions in Python

ZeroDivisionError:

This error arises when an attempt is made to divide a number by zero. Division by zero is undefined in mathematics, causing an arithmetic error.

ValueError:

This error occurs when an inappropriate value is used within the code. An example of this is when trying to convert a non-numeric string to an integer.

FileNotFoundError:

This exception is encountered when an attempt is made to access a file that does not exist.

IndexError:

An IndexError occurs when an index is used to access an element in a list that is outside the valid index range.

KeyError:

The KeyError arises when an attempt is made to access a non-existent key in a dictionary.

TypeError:

The TypeError occurs when an object is used in an incompatible manner. An example includes trying to concatenate a string and an integer.

AttributeError:

An AttributeError occurs when an attribute or method is accessed on an object that doesn't possess that specific attribute or method.

ImportError:

This error is encountered when an attempt is made to import a module that is unavailable.

Many more exceptions can be encountered. The documentation is available in Python Documentation Library.

Examples

Handling Generic Exceptions

Task: I need to define a function that performs a complex mathematical task. This task involves dividing a given number, "num", by the difference between "num" and 5. The result of this calculation needs to be stored in a variable called "result".

To handle any potential errors during the calculation, I'll use a try-except block. If an exception occurs, I'll catch it using the generic exception class "Exception" and assign it to the variable "e". In case of an exception, the function should display "Error". This task is part of my course assignment.

Output: TypeError

Since it yieled a TypeError:, I was able to see that a parameter has to be placed inside the def function.

Handling ValueError

I needed to create a Python function to calculate the square root of a given number. I named the input parameter 'number1'.

The function was designed to compute the square root if a positive integer or float was provided as input. However, it also had to be smart enough to detect mistakes, such as negative values. In such cases, it should kindly inform the user with the message, 'Invalid input! Please enter a positive integer or a float value.'

This task was part of my course assignment.

Running the code if it's working properly.

Handling ZeroDivisionError

I needed to create a Python function named safe_divide to handle division between two numbers. The function takes two inputs: a 'numerator' and a 'denominator', which are obtained using the user input method in Python.

The function should perform the division and return the result. However, it needed to be smart enough to handle the scenario where the denominator is zero, which is not allowed in math. Instead of throwing an error, the function should return None and print "Error: Cannot divide by Zero."


Source Disclosure:

In this blog post, I discussed key concepts and my learning thoughts from IBM Data Science Professional Certificate by IBM and Coursera. The course is designed to provide the building blocks for Python programming, specifically to exception handling. You can find more information about the course Python for Data Science, AI & Development | Coursera.