Python Try Except

Python Try Except  #

The try block lets you test a block of code for errors.

try блок нь блок кодын алдааг шалгах боломжийг олгодог.

The except block lets you handle the error.

except блок нь алдааг засах боломжийг олгодог.

The else block lets you execute code when there is no error.

else блок нь алдаа гараагүй үед кодыг ажиллуулах боломжийг олгодог.

The finally block lets you execute code, regardless of the result of the try- and except blocks.

finally блок нь try болон except блокуудын үр дүнгээс үл хамааран кодыг ажиллуулах боломжийг олгодог.

Exception Handling – Онцгой байдлын зохицуулалт #

When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

Алдаа эсвэл exception гарсан үед Python ихэвчлэн зогсож, алдааны мессеж гаргадаг.

These exceptions can be handled using the try statement:

Эдгээр алдааг try хэллэг ашиглан засаж болно:

Example – Жишээ #

The try block will generate an exception, because x is not defined:

try блок нь x-ыг тодорхойлогдоогүй учраас алдаа үүсгэнэ:

try:
  print(x)
except:
  print("An exception occurred")

Since the try block raises an error, the except block will be executed.

try блокт алдаа гаргасан тул except блок ажиллана.

Without the try block, the program will crash and raise an error:

try блокгүйгээр програм эвдэрч, алдаа гаргана:

Example – Жишээ #

This statement will raise an error, because x is not defined:

Энэ мэдэгдэлд алдаа гаргана, учир нь x тодорхойлогдоогүй:

print(x)

Many Exceptions – Олон тайлбарууд #

You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error:

Та хэдэн ч удаагийн алдаа гаргагч блокуудыг тодорхойлж болно. Жишээлбэл, тодорхой нэг төрлийн алдаа гаргах үед гүйцэтгэх тусгай кодын блокыг оруулахыг хүсвэл:

Example – Жишээ #

Print one message if the try block raises a NameError and another for other errors:

Хэрэв try блок нь NameError алдаа үүсгэвэл нэг мессежийг хэвлэж, бусад алдааны үед өөр мессежийг хэвлэнэ:

try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")

Else #

You can use the else keyword to define a block of code to be executed if no errors were raised:

Та ямар нэгэн алдаа гаргаагүй бол else түлхүүр үгийг ашиглаж гүйцэтгэх блок кодыг тодорхойлж болно.

Example – Жишээ #

In this example, the try block does not generate any error:

Энэ жишээнд try блок алдаа үүсгэхгүй:

try:
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")

Finally  #

The finally block, if specified, will be executed regardless if the try block raises an error or not.

finally блок, хэрэв заагдсан бол, try блок алдаа үүсгэх эсэхээс үл хамааран ажиллана.

Example – Жишээ #

In this example, the try block does not generate any error:

Энэ жишээнд try блок алдаа үүсгэхгүй:

try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")

This can be useful to close objects and clean up resources:

Энэ нь объектуудыг хаах болон нөөцийг цэвэрлэхэд тустай байж болно:

Example – Жишээ #

Try to open and write to a file that is not writable:

Бичих боломжгүй файлыг нээж бичихийг оролдох:

try:
  f = open("demofile.txt")
  try:
    f.write("Lorum Ipsum")
  except:
    print("Something went wrong when writing to the file")
  finally:
    f.close()
except:
  print("Something went wrong when opening the file")

The program can continue, without leaving the file object open.

Програм үргэлжлэх бөгөөд файл нээлттэй хэвээр үлдэхгүй.

Raise an exception – Тайлбар нэмэх #

As a Python developer you can choose to throw an exception if a condition occurs.

Python хөгжүүлэгчид зарим нөхцөл байдал үүссэн үед exception-ийг үүсгэж (throw) болно.

To throw (or raise) an exception, use the raise keyword.

Exception-ийг үүсгэхийн тулд raise түлхүүр үгийг ашиглана.

Example – Жишээ #

Raise an error and stop the program if x is lower than 0:

x нь 0-ээс бага бол алдаа үүсгэж, програмыг зогсоо:

x = -1
if x < 0:
  raise Exception("Sorry, no numbers below zero")

The raise keyword is used to raise an exception.

raise түлхүүр үгийг ашиглан exception-ийг үүсгэж болно.

You can define what kind of error to raise, and the text to print to the user.

Ямар төрлийн алдаа үүсгэхийг болон хэрэглэгчид ямар текстийг харуулахыг тодорхойлж болно.

Example – Жишээ #

Raise a TypeError if x is not an integer:

x бүхэл тоо биш бол TypeError үүсгэх:

x = "hello"
if not type(x) is int:
  raise TypeError("Only integers are allowed")

Powered by BetterDocs

Leave a Reply