Lokang 

Python and MySQL

exception

ValueError

ValueError is a built-in exception in Python that is raised when a built-in operation or function receives an argument that has the right type but an inappropriate value. For example, when passing a string that cannot be converted to an int to the int() function, a ValueError is raised:

try:
   value = int("abc")
except ValueError:
   print("Could not convert the string to an integer.")

In this example, the try block contains the code that may raise an exception (the call to int("abc")). If the argument passed to int() is not a valid integer representation, a ValueError is raised and the code inside the corresponding except block is executed.

You can also raise a ValueError manually in your own code if you need to indicate that a specific value is not valid for a given function or operation:

def square_root(value):
   if value < 0:
       raise ValueError("The argument must be a positive number.")
   return value ** 0.5
try:
   result = square_root(-4)
except ValueError as error:
   print(error)

In this example, the square_root function raises a ValueError if the argument passed to it is negative, indicating that the square root of a negative number is not a real number. If the function is called with a negative argument, the ValueError is raised and caught in the try-except block, printing the error message.

 

 

TypeError

TypeError is a built-in exception in Python that is raised when an operation or function is applied to an object of inappropriate type. For example, when trying to perform arithmetic operations on incompatible types, such as concatenating a string and an int, a TypeError is raised:

try:
   value = "abc" + 123
except TypeError:
   print("Cannot concatenate a string and an int.")

In this example, the try block contains the code that may raise an exception (the concatenation of a string and an int). If the operands passed to the addition operator are not both of the same type, a TypeError is raised and the code inside the corresponding except block is executed.

You can also raise a TypeError manually in your own code if you need to indicate that a specific type is not valid for a given function or operation:

def divide(a, b):
   if not isinstance(b, (int, float)):
       raise TypeError("The second argument must be a number.")
   return a / b
try:
   result = divide(4, "2")
except TypeError as error:
   print(error)

In this example, the divide function raises a TypeError if the second argument passed to it is not a number (i.e., an instance of int or float), indicating that division can only be performed between numbers. If the function is called with a second argument that is not a number, the TypeError is raised and caught in the try-except block, printing the error message.

 

IndexError

IndexError is a built-in exception in Python that is raised when a sequence subscript is out of range. A sequence in Python can be any iterable object, such as a list, tuple, or string. If you try to access an element of a sequence using an index that is outside the range of valid indices, a IndexError is raised:

try:
   list = [1, 2, 3]
   print(list[3])
except IndexError:
   print("The index is out of range.")

In this example, the try block contains the code that may raise an exception (the access to the fourth element of a list with only three elements). If the index passed to the list is greater than or equal to the length of the list, a IndexError is raised and the code inside the corresponding except block is executed.

You can also raise a IndexError manually in your own code if you need to indicate that a specific index is not valid for a given sequence:

def get_element(list, index):
   if index >= len(list):
       raise IndexError("The index is out of range.")
   return list[index]
try:
   result = get_element([1, 2, 3], 3)
except IndexError as error:
   print(error)

In this example, the get_element function raises a IndexError if the index passed to it is greater than or equal to the length of the list, indicating that the index is out of range. If the function is called with an index that is out of range, the IndexError is raised and caught in the try-except block, printing the error message.

 

KeyError

found in the dictionary. A dictionary is a collection of key-value pairs, where each key is unique and maps to a corresponding value. If you try to access the value of a key that is not in the dictionary, a KeyError is raised:

try:
   dictionary = {"a": 1, "b": 2, "c": 3}
   print(dictionary["d"])
except KeyError:
   print("The key is not in the dictionary.")

In this example, the try block contains the code that may raise an exception (the access to the value of the key "d" in a dictionary that only contains keys "a", "b", and "c"). If the key passed to the dictionary is not found in the dictionary, a KeyError is raised and the code inside the corresponding except block is executed.

You can also raise a KeyError manually in your own code if you need to indicate that a specific key is not valid for a given dictionary:

def get_value(dictionary, key):
   if key not in dictionary:
       raise KeyError("The key is not in the dictionary.")
   return dictionary[key]
try:
   result = get_value({"a": 1, "b": 2, "c": 3}, "d")
except KeyError as error:
   print(error)

In this example, the get_value function raises a KeyError if the key passed to it is not found in the dictionary, indicating that the key is not in the dictionary. If the function is called with a key that is not in the dictionary, the KeyError is raised and caught in the try-except block, printing the error message.

 

 

NameError

NameError is a built-in exception in Python that is raised when a name is not found in the namespace. A namespace is a collection of names that are associated with values or objects. If you try to use a name that is not defined in the current namespace, a NameError is raised:

try:
   print(undefined_variable)
except NameError:
   print("The variable is not defined.")

In this example, the try block contains the code that may raise an exception (the access to the value of the undefined variable undefined_variable). If the variable passed is not defined in the namespace, a NameError is raised and the code inside the corresponding except block is executed.

You can also raise a NameError manually in your own code if you need to indicate that a specific name is not valid for a given namespace:

def get_variable(name):
   if name not in globals():
       raise NameError("The variable is not defined.")
   return globals()[name]
try:
   result = get_variable("undefined_variable")
except NameError as error:
   print(error)

In this example, the get_variable function raises a NameError if the name passed to it is not found in the global namespace, indicating that the variable is not defined. If the function is called with a name that is not in the global namespace, the NameError is raised and caught in the try-except block, printing the error message.

 

 

ZeroDivisionError

ZeroDivisionError is a built-in exception in Python that is raised when an operation is attempted to be performed that would result in a division by zero. This is generally considered an invalid operation, and so Python raises the ZeroDivisionError exception:

try:
   result = 5 / 0
except ZeroDivisionError:
   print("Cannot perform division by zero.")

In this example, the try block contains the code that may raise an exception (the division of 5 by 0). If the division by zero is attempted, a ZeroDivisionError is raised and the code inside the corresponding except block is executed.

You can also raise a ZeroDivisionError manually in your own code if you need to indicate that a specific division is not valid:

def divide(dividend, divisor):
   if divisor == 0:
       raise ZeroDivisionError("Cannot perform division by zero.")
   return dividend / divisor
try:
   result = divide(5, 0)
except ZeroDivisionError as error:
   print(error)

In this example, the divide function raises a ZeroDivisionError if the divisor passed to it is zero, indicating that the division is not valid. If the function is called with a divisor of zero, the ZeroDivisionError is raised and caught in the try-except block, printing the error message.

 

 

ImportError

ImportError is a built-in exception in Python that is raised when an import statement fails to find the specified module or package. This can occur if the module or package does not exist in the specified location, or if there is a syntax error in the import statement:

try:
   import non_existent_module
except ImportError:
   print("The specified module could not be found.")

In this example, the try block contains the code that may raise an exception (the import of the non_existent_module). If the module does not exist, a ImportError is raised and the code inside the corresponding except block is executed.

You can also raise an ImportError manually in your own code if you need to indicate that a specific module or package cannot be imported:

def import_module(module_name):
   try:
       __import__(module_name)
   except ImportError:
       raise ImportError(f"The module '{module_name}' could not be imported.")
try:
   import_module("non_existent_module")
except ImportError as error:
   print(error)

In this example, the import_module function raises an ImportError if the specified module cannot be imported. If the function is called with a non-existent module name, the ImportError is raised and caught in the try-except block, printing the error message.