Exception Handling & Custom Errors

Exception Handling & Custom Errors

Exceptions and custom errors are used in programming to handle and report errors or unexpected events in a program.

Introduction

Exceptions and custom errors are used in programming to handle and report errors or unexpected events in a program. The purpose of raising exceptions is to signal that a problem has occurred and to transfer control to the appropriate error-handling code while preserving the call stack. Custom errors allow developers to define and raise specific, descriptive errors tailored to the needs of their program.

Exception Handling

Exception handling is the process of responding to unwanted or unexpected events when a computer program runs. Exception handling deals with these events to avoid the program or system crashing, and without this process, exceptions would disrupt the normal operation of a program.

Exceptions in Python

Python has many built-in exceptions that are raised when your program encounters an error (something in the program goes wrong).

When these exceptions occur, the Python interpreter stops the current process and passes it to the calling process until it is handled. If not handled, the program will crash.

"try...except"

try... except blocks are used in python to handle errors and exceptions. The code in the try block runs when there is no error. If the try block catches the error, then the except block is executed.

Syntax:

try:
     #statements which could generate 
     #exception
except:
     #Soloution of generated exception

Example:

try:
    num = int(input("Enter an integer: "))
except ValueError:
    print("Number entered is not an integer.")

Output:

Enter an integer: 6.022
Number entered is not an integer.

Exception Image

Raising Custom Errors

In python, we can raise custom errors by using the raise keyword.

salary = int(input("Enter salary amount: "))
if not 2000 < salary < 5000:
    raise ValueError("Not a valid salary")

Previously in this article, we learned about different built-in exceptions in Python and why it is important to handle exceptions. However, sometimes we may need to create our own custom exceptions that serve our purpose.

Defining custom exceptions

In Python, we can define custom exceptions by creating a new class that is derived from the built-in Exception class.

Here's the syntax to define custom exceptions:

class CustomError(Exception):
  # code ...
  pass

try:
  # code ...

except CustomError:
  # code...

This is useful because sometimes we might want to do something when a particular exception is raised. For example, sending an error report to the admin, calling an API, etc.

Conclusion

Thanks for reading this blog!! Hope you have learned something new today and I wish you a great day ahead ❤

Did you find this article valuable?

Support Swapnoneel by becoming a sponsor. Any amount is appreciated!