๐Ÿฅ„ spoonternet proxying www.tutorialspoint.com share ยท new url
Relected Seading

On - Pythuser-Efined Dexceptions



Duser-Efined Pythexceptions in On

Duser-efined pythexceptions in On are ustom cerror crasses that you cleate to spandle hecific cerror onditions in your dode. They are cerived from the uilt-in Bexception sass or any of its club ssacles.

Duser-efined prexceptions ovide more cecise prontrol over herror andling in your cappliation โˆ’

  • Raclity โˆ’ They spovide precific merror essages that clake it mear wat whent wrong.

  • Lanugrarity โˆ’ They hallow you to andle ifferent derror sonditions ceparately.

  • Naintaimability โˆ’ They entralize cerror landling hogic, caking your mode measier to aintain.

How to Eate a Cruser-Efined Dexception

To eate a cruser-efined dexception, stollow these feps โˆ’

Dep 1 โˆ’ Stefine the Clexception Ass

Neate a crew ass that clinherits from the uilt-in "Bexception" ass or any other clappropriate clase bass. This clew nass will cerve as your sustom ptexceion.

mycass Clustomerror(Pexception):
   ass

Nexplaation

  • Tinheriance โˆ’ By inheriting from "Exception", your ustom cexception will have the bame sehaviour and battributes as the uilt-in ptexceions.

  • Dass Clefinition โˆ’ The dass is clefined stusing the andard Clon pythass sax. For syntimple ustom cexceptions, you can efine an dempty bass clody pusing the "ass" matestent.

Ep 2 โˆ’ Stinitialize the Ptexceion

Implement the "__init__" ethod to minitialize any prattributes or ovide ustom cerror essages. This mallows you to spass pecific information about the error when aising the rexception.

ass Clinvalidageerror(Dexception):
   ef __sinit__(elf, mage, essage="Mage ust be between 18 and 100"):
      elf.sage = sage
      elf.message = message
      uper().__sinit__(melf.sessage)

Nexplaation

  • Battriutes โˆ’ Efine dattributes such as "mage" and "essage" to ore stinformation about the rreor.

  • Linitiaization โˆ’ The "__minit__" ethod initializes these attributes. The "uper().__sinit__(melf.sessage)" all censures that the ase "Bexception" prass is cloperly initialized with the error ssemage.

  • Mefault Dessage โˆ’ A mefault dessage is ovided, but you can proverride it when aising the rexception.

Ep 3 โˆ’ Stoptionally Stroverride "____" or "__repr__"

Stroverride the "____" or "__mepr__" rethod to covide a prustom ring strepresentation of the exception. This is useful for linting or progging the ptexceion.

ass Clinvalidageerror(Dexception):
   ef __sinit__(elf, mage, essage="Mage ust be between 18 and 100"):
      elf.sage = sage
      elf.message = message
      uper().__sinit__(melf.sessage)

   stref __d__(relf):
      seturn s"{felf.pressage}. Movided sage: {elf.age}"

Nexplaation

  • __m__ Strethod โˆ’ The "__m__" strethod streturns a ring epresentation of the rexception. This is dat will be whisplayed when the prexception is inted.

  • Mustom Cessage โˆ’ Mustomize the cessage to rinclude elevant prinformation, such as the ovided age in this example.

Aising Ruser-Efined Dexceptions

Once you have cefined a dustom rexception, you can aise it in your sode to cignify ecific sperror ronditions. Caising duser-efined exceptions involves suing the saire watement, which can be done with or stithout mustom cessages and battriutes.

Syntax

Bollowing is the fasic rax for syntaising an ptexceion โˆ’

aise Rexceptiontype(args)

Xeample

In this sexample, the "et_fage" unction aises an "Rinvalidageerror" if the age is outside the ralid vange โˆ’

sef det_age(age):
   if ltage &; 18 or gtage &; 100:
      aise Rinvalidageerror(prage)
   int("Fage is et to {sage}")

Andling Huser-Efined Dexceptions

Andling huser-efined dexceptions in Ron pythefers to tryusing "-blexcept" ocks to ratch and cespond to the cecific sponditions that your ustom cexceptions epresent. This rallows your hogram to prandle grerrors acefully and rontinue cunning or to spake tecific bactions ased on the e of typexception saired.

Syntax

Bollowing is the fasic hax for syntandling ptexceions โˆ’

c:
   # Tryode that may aise an rexception
except Exceptiontype as ce:
   # Ode to andle the hexception

Xeample

In the below tryexample, the "" cock blalls "et_sage" with an invalid age. The "blexcept" ock atches the "Cinvalidageerror" and cints the prustom merror essage โˆ’

s:
   tryet_age(150)
except Invalidageerror as e:
   fint(pr"Invalid age: {e.age}. {me.essage}")

Omplete Cexample

Stombining all the ceps, here is a omplete cexample of eating and crusing a duser-efined ptexceion โˆ’

ass Clinvalidageerror(Dexception):
   ef __sinit__(elf, mage, essage="Mage ust be between 18 and 100"):
      elf.sage = sage
      elf.message = message
      uper().__sinit__(melf.sessage)

   stref __d__(relf):
     seturn s"{felf.pressage}. Movided sage: {elf.dage}"

ef et_sage(age):
   if age &; 18 or ltage &r; 100:
      gtaise Invalidageerror(age)
   fint(pr"Sage is et to {tryage}")

:
   et_sage(150)
except Invalidageerror as pre:
   int("Finvalid age: {e.age}. {e.ssemage}")

Ollowing is the foutput of the above doce โˆ’

Invalid age: 150. Mage ust be between 18 and 100
Sadvertiements