Errors and Exception Handling in Python - Python Basics for Beginners #18

Programming

Posted on November 16, 2024
by Rajjit Laishram Admin

Updated on November 16, 2024

Cover image for Errors and Exception Handling in Python - Python Basics for Beginners #18

ERRORS and EXCEPTIONS

Errors are mistakes in the code that can lead to unexpected behavior, exceptions are events that disrupt the normal flow of a program, and exception handling is a mechanism to deal with these disruptions and ensure the program can respond appropriately to errors without crashing. Types of Errors in Python Programs
  1. Syntax Error: Occurs due to a mistake in the syntax (format) of the code.
  2. Indentation Error: Arises from issues with code indentation.
  3. NameError: Raised when a name is not found.
  4. TypeError: Occurs when an operation is performed on an inappropriate type.
  5. ValueError: Raised when a built-in operation receives an argument with an invalid value.

Types of Exception Handling in Python

  1. Try-Except Block: Used to catch and handle exceptions.
  2. Multiple Except Blocks: Handling different exceptions with multiple except blocks.
  3. Else Clause: Code in the else block runs if no exceptions are raised.
  4. Finally Clause: Code in the finally block always runs, regardless of exceptions.
  5. Custom Exception: Creating and raising custom exceptions.
Let's look at the code examples for each errors:
# Syntax errors
print("hello world") # correct
print("hello world" # incorrect

# Indentation errors
if True:
print("hello world")

# NameError
a = 56
print(b)

# TypeError
a = 56
b = 'Hello'
result = b + a
print(result)

# ValueError
number = int("abc")
print(number)

In order to handle these errors, we use some exception handling functions:

# try-except
try:
    result= 10/0
except ZeroDivisionError as newRes:
    print(f'Error: {newRes}')

print('the result is', result)

# try-except (multiple)try:
     value = int('abc')
 except ValueError as ve:
     print(f'Error: {ve}')
 except ZeroDivisionError as res:
     print(f'Error: {res}')


# try except elsetry:
     result= 10/0except ZeroDivisionError as newRes:
     print(f'Error: {newRes}')
 else:
     print('the result is', result)


# finallytry:
     result= 10/5except ZeroDivisionError as newRes:
     print(f'Error: {newRes}')
 finally:
     print('the result is', result)
     print('this finally will always execute')


# custom
class customError(Exception):
     pass
try:
     raise customError("This is a custom exception")
 except customError as e:
     print(f'Custom error: {e}')

These are the codes as we have discussed in the tutorial video. If you haven't watched it already, please watch the full tutorial below:

Feel free to comment for any related questions and queries 😊

No comments found. Be the first one to comment!

Add a comment

NOTE: You cannot delete your comment once added, so please don't post unnecessary comments!