Bytes

Exception Handling in Python

Exceptions are mistakes discovered during execution. Exceptions are triggered whenever there is a mistake in a program. The program will come to a standstill if these exceptions are not handled. Python exception handling is essential to prevent the program from ending unexpectedly. This post will go over Exception Handling in Python in further detail.

What is Exception Handling in Python?

Exception handling in Python is a process of resolving errors that occur in a program. This involves catching exceptions, understanding what caused them, and then responding accordingly. Exceptions are errors that occur at runtime when the program is being executed. They are usually caused by invalid user input or code that is invalid in Python. Exception handling allows the program to continue to execute even if an error occurs.

Syntax:

Loading...

This is an example of the syntax for handling exceptions in Python. A try block contains code that can throw an exception ⚠️. If an exception occurs, the code in the except block is executed, which helps to handle the Exception. The else block is optional and is only executed if no exceptions occur. Finally, the code inside the finally block will always be executed regardless of any exceptions💯 .

Common Exceptions in Python

  1. NameError: This Exception is raised when a name is not found in the local or global namespace.
  2. IndexError: This Exception is raised when an invalid index is used to access a sequence.
  3. KeyError: This Exception is thrown when the key is not found in the dictionary.
  4. ValueError: This Exception is thrown when a built-in operation or function receives an argument of the correct type and incorrect value.
  5. IOError: This Exception is raised when an input/output operation fails, such as when an attempt is made to open a non-existent file.
  6. ImportError: This Exception is thrown when an import statement cannot find a module definition or a from ... import statement cannot find a name to import.
  7. SyntaxError: This Exception is raised when the input code does not conform to the Python syntax rules.
  8. TypeError: This Exception is thrown when an operation or function is applied to an object of inappropriate type
  9. AttributeError: occurs when an object does not have an attribute being referenced, such as calling a method that does not exist on an object.
  10. ArithmeticError: A built-in exception in Python is raised when an arithmetic operation fails. This Exception is a base class for other specific arithmetic exceptions, such as ZeroDivisionError and OverflowError.
  11. Floating point error: It is a type of arithmetic error that can occur in Python and other programming languages that use floating point arithmetic to represent real numbers.
  12. ZeroDivisionError: This occurs when dividing a number by zero, an invalid mathematics operation.
  13. FileExistsError: This is Python's built-in Exception thrown when creating a file or directory already in the file system.
  14. PermissionError: A built-in exception in Python is raised when an operation cannot be completed due to a lack of permission or access rights.

Try Except in Python

Python provides a way to catch specific exceptions during a program's execution. This is done with the "try" statement. The basic syntax looks like this:

Loading...

For example, if we wanted to catch a ZeroDivisionError, we could do something like this:

Loading...

This code will print "You can't divide by zero!" if a ZeroDivisionError is encountered during execution.

Raising Custom Exceptions in python

You can create custom exceptions in Python by creating a new exception class. To create a custom exception, you must define a new class inherited from the Exception class. You can add custom attributes, methods, and other logic to your custom exceptions as needed. Example:

Loading...

This code creates a custom exception class called CustomError. This exception class inherits from the base Exception class and has a custom message attribute. When the Exception is raised, the message is passed to the init  method and set as the message attribute. In the except block, the message attribute is printed.

Try except and ELSE!

Try and Except in Python is a way of handling errors and exceptions in Python. It is used to catch any errors that may occur during the execution of a program and provide a graceful way to handle them. The syntax for using try and except is as follows:

Loading...

The code inside the try block is executed until an exception is raised. If an exception is raised, the code inside the except block is executed. The code inside the else block is executed if no exception is raised.

Try Clause with Finally

Loading...

This code divides the variable x (set to 5) by the variable y (set to 0). Since this is impossible (dividing by 0), the code will throw a ZeroDivisionError. The except statement catches this error and prints a message to the user. The finally statement will run regardless of whether or not an error occurs, and in this case, it prints "All done".

Why Use Finally or Else in try..except?

Finally and Else are two keywords used in try..except blocks in Python. The Finally block executes a set of statements, regardless of the result of the try..except blocks. This is useful when you want to clean up resources like closing a file or connection, irrespective of whether an exception occurred or not. The Else block is used to execute a set of statements only if the try block does not raise an exception. It is useful for code that must be executed if the try block does not raise an exception.

What Happens if Errors are Raised in Except or Finally Block?

If an error is raised in an except or finally block, the error will be handled by the next outer try-except statement, or if there is no outer try-except statement, the error will be raised to the caller.

Loading...

This code is trying to divide 1 by 0, which will raise a ZeroDivisionError. This error is handled by the except block, which prints out "Division by zero not allowed". Then, the finally block tries to print the variable y, which is not defined. This raises a NameError, which is handled by the inner try-except statement in the finally block, which prints out "Variable y is not defined".

Conclusion

We learned about Exception Handling in Python, including how to raise and catch exceptions, use try-except blocks, create custom exceptions, and use the finally clause. We can now use our newfound knowledge to handle errors and exceptions in her Python code, enabling us to write more robust and reliable programs. 

Key takeaways

  1. Always use try-except blocks when catching exceptions
  2. Use finally to clean up resources that were used or allocated in the try block
  3. When handling exceptions, use specific exception handlers for specific exceptions
  4. Use raise to throw a custom exception 🚩
  5. Use logging to log exceptions for later debugging
  6. Use assertions to validate the correctness of code 🔍
  7. Always document the exceptions that a function or method can raise

Quiz

  1. What is the correct syntax for raising an exception? 
    1. raise Exception 
    2. throw Exception  
    3. exit Exception 
    4. exit()

Answer: a. raise Exception

  1. What is the correct syntax to catch an exception in Python? 
    1. except Exception 
    2. catch Exception  
    3. try Exception 
    4. handle Exception

Answer:a. except Exception

  1. When will a finally block be executed in a try-except-finally statement?
    1. When an exception is caught  
    2. When an exception is not caught 
    3. After the try statement is executed 
    4. After the except statement is executed

Answer:c. After the try statement is executed

  1. What is the purpose of an else block in a try-except-else statement? 
    1. To execute code if an exception is not thrown  
    2. To execute code if an exception is thrown  
    3. To execute code regardless of whether an exception is thrown  
    4. To execute code after the try and except blocks are executed

Answer:a. To execute code if an exception is not thrown

Module 6: Functions in PythonException Handling in Python

Top Tutorials

Related Articles

AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter