PYTHON

Errors and Exceptions


Errors and exceptions are integral parts of programming in Python, helping developers manage and respond to unexpected events. Understanding the differences between errors and exceptions, and knowing how to handle them properly, is crucial for writing reliable code.

 

1. Types of Errors

1.1 Syntax Errors

Syntax errors occur when the parser detects an incorrect statement. These are detected before the program is executed.

Example:

# SyntaxError: invalid syntax
if True
   print("Hello")
 

1.2 Runtime Errors

Runtime errors occur during the execution of the program. They are also known as exceptions.

Example:

# ZeroDivisionError: division by zero
print(10 / 0)
 

 

2. Exceptions

Exceptions are runtime errors that can be caught and handled to prevent the program from crashing. Python provides a variety of built-in exceptions, and you can also define custom exceptions.

 

 

3. Built-in Exceptions

Common Built-in Exceptions:

  • ValueError: Raised when a function receives an argument of the correct type but inappropriate value.
  • TypeError: Raised when an operation or function is applied to an object of inappropriate type.
  • IndexError: Raised when a sequence subscript is out of range.
  • KeyError: Raised when a dictionary key is not found.
  • AttributeError: Raised when an attribute reference or assignment fails.
  • FileNotFoundError: Raised when a file or directory is requested but doesn't exist.
  • ZeroDivisionError: Raised when the second operand of a division or modulo operation is zero.

 


PYTHON