Try Block in Python


In Python, the try block is used to enclose code that might raise an exception. If an exception is raised within the try block, the code in the corresponding except block is executed. This allows you to handle errors and exceptions in a controlled way, rather than letting the program crash.

The try block in Python is used to enclose code that might raise an exception. If an exception is raised within the try block, it is caught by the associated except block, which can then handle the exception as desired. The basic structure of a try-except block in Python is as follows:

Syntax:
   try:
              # code that might raise an exception
   except ExceptionType1:
              # code to handle ExceptionType1
   except ExceptionType2:
              # code to handle ExceptionType2
   except:
              # code to handle any other exception
   else:
              # code to run if no exception was raised
   finally:
              # code that will always be executed, regardless of whether an exception was raised or not

The else block is optional, and is only executed if no exceptions were raised within the try block. The finally block is also optional, but is always executed after the try block, regardless of whether an exception was raised or not.


Source Code

"""
# try block in Python
try:
    a = 10 / 0
except Exception as e:
    print(e)
 
# Try Else
try:
    a = 10 / 25
except Exception as e:
    print(e)
else:
    print("A Value : ",a)
 
# Try else finally
try:
    a = 10 / 0
except Exception as e:
    print(e)
else:
    print("A Value : ",a)
finally:
    print("Thank You")
 
 
# Type of Exceptions in Python
print(dir(locals()['__builtins__']))
print(len(dir(locals()['__builtins__'])))
 
# Nameerror Exception
 
 
try:
    print(a)
except NameError as e:
    print("A is not Defined")
 
try:
    print(10 / 0)
except ZeroDivisionError as e:
    print("denominator cant be zero")
 
try:
    a = int("Joes")
except ValueError as e:
    print("Please Enter Numbers only")
 
try:
    a = [10, 20, 30, 40]
    print(a[10])
except IndexError as e:
    print("Invalid Index")
 
try:
    f = open("tesot.txt")
except FileNotFoundError:
    print("File Not Found")
else:
    print(f.read())
"""
 
try:
    a=10/20
    print(a)
    b=[10,20,30,40]
    print(b[0])
    a=open('ramu.txt')
except ZeroDivisionError:
    print("denominator cant be zero")
except IndexError:
    print("Invalid Index")
except Exception as e:
    print(e)
 
 
 
To download raw file Click Here

Output

# try block in Python
division by zero

# Try Else
A Value :  0.4

# Try else finally
division by zero
Thank You

# Type of Exceptions in Python
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
153

# Type of Exceptions 
A is not Defined
denominator cant be zero
Please Enter Numbers only
Invalid Index
File Not Found

List of Programs


Sample Programs


Python Database Connection


Python Flask


Python Tkinder Tutorial