fbpx

Exception Handling

Built-in exceptions

Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that are raised when corresponding errors occur. We can view all the built-in exceptions using the built-in local() function as follows:

				
					print(dir(locals()['__builtins__']))

				
			

 

In Python, you can also create or “raise” your own exceptions

The simplest format for a raise command is the keyword raise followed by the name of an exception.

				
					def main()
  A()

def A():
  B()

def B():
  C()

def C():
  D()

def D()
  try:
    # processing code
    if something_special_happened:
      raise MyException
  except MyException:
    # execute if the MyException message happenedconsole.log( 'Code is Poetry' );
				
			

Exception handling is a way of handling runtime errors and exceptional situations that occur while a program is running. When an error occurs in Python, it generates an exception object that describes the error and stops the normal execution of the program. To handle these exceptions and continue program execution, Python provides a try-except block.

				
					try:
    # code that may raise an exception
except ExceptionType:
    # code to handle the exception

				
			

In this syntax, the try block contains the code that may raise an exception. If an exception occurs, Python will stop executing the try block and jump to the except block. The except block contains code to handle the exception. The ExceptionType parameter is optional and can be used to specify the type of exception to catch. If no ExceptionType is specified, the except block will catch all exceptions.

Here is an example of a try-except block in Python:

				
					try:
    x = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

				
			

Try...finally

Python also provides a finally block that can be used to execute cleanup code regardless of whether an exception was raised. The syntax for a try-finally block is as follows:

				
					try:
   f = open("test.txt",encoding = 'utf-8')
   # perform file operations
finally:
   f.close()

				
			

In this syntax, the finally block contains code that will always be executed, regardless of whether an exception was raised or not.


Here is an example of a try-except-finally block in Python:

				
					try:
    f = open("myfile.txt")
    # do something with the file
except IOError:
    print("Error opening file")
finally:
    f.close()

				
			

In this example, the try block attempts to open a file called “myfile.txt”, which may raise an IOError exception. The except block catches the exception and prints an error message. The finally block closes the file, regardless of whether an exception was raised or not.

Loading...