raise keyword in python

Previous
Next

raise:

  • It is a keyword.
  • It is used to raise Custom Exception explicitly by the programmer.
  • Pre-defined exceptions will be raised automatically when problem occurs.
  • If we don’t handle the exception, Default Exception Handler handles.
class CustomError(Exception):
    def __init__(self,name):
        self.name=name
        return

class RaiseException:
    def main():
        obj = CustomError("Error-Msg")
        raise obj
        return

RaiseException.main()

Handling Custom Exception:

  • Generally exception rises inside the function.
  • We need to handle the exception while calling the function.
  • When exception has raised, the object will be thrown to function calling area.
class CustomError(Exception):
    def __init__(self,name):
        self.name=name
        return

class Test:
    def fun():
        obj = CustomError("Message")
        raise obj
        return
    
class Access:
    def main():
        try:
            Test.fun()
        except CustomError as e:
            print("Exception :",e)
        return

Access.main()
Previous
Next

Add Comment

Courses Enquiry Form