How To Handle Exceptions (3 Min) In Python | Learn Error & Exception Handling
In this tutorial, you'll learn how to handle exceptions in Python.
—
Facebook: https://www.facebook.com/GokceDBsql
—
Video Transcript:
—
Hi guys, this is Abhi from Gokcedb. In this video, you're going to learn how to handle exceptions in Python. Let's start by looking at the try block on line 3.
I'm accepting the first number as input from the user. On line 5, I'm accepting the second number. Next, I'm using the erase keyword to raise an exception if num2 is equal equal to 7.
On line 8, I'm printing the result of dividing num1 by num2. On line 9, I'm using the accept keyword to catch the 0 division if num2 is equal to zero. Next, let's test this out by inputting the second number as zero.
The reason you see goodbye in the output is that I have a final block where I'm printing goodbye which gets executed every time irrespective of whether there was an exception or not. On line 11, I'm catching a value error in case the number provided is not a numerical value. On line 13, I'm catching keyword interrupt in case the execution of the program is interrupted by the user by pressing the stop button or say by passing CRTL C on the command line.
Line 15, I'm catching all the exceptions that were not caught by the above except blocks. If we go back to line 7, you'll see that I'm using the erase keyword to raise an exception if num2 is equal equal to 7. Let's see what happens when I input 7 as the second number.
Looks like we caught the type error exception in this generic exception block. Note the accept exception block catches all the subclasses of the exception class. If you look at the UML diagram of the zero division error class, you'll see that it inherits from the exception class.
Similarly, value error is also a subclass of the exception class. However, if you look at the UML diagram of keyboard interrupt, you'll notice that it inherits from the base exception class and not the exception class. That's because keyboard interrupt is a system-level exception.
Therefore to catch all the system lever exceptions in addition to regular exceptions you have to define an accept base exception block. Here I commented out except keyboard interrupt block to see if except base exception block catches it. Finally, if we rerun the program and no exception is found then the else block will also get executed.
There you have it. Make sure you like, subscribe, and turn on the notification bell. Until next time.
try:
print("Enter the first number:")
num1 = int(input())
print("Enter the second number:")
num2 = int(input())
if num2 == 7:
raise "Not 7"
print("Here's the result of dividing num1/num2:", num1/num2)
except ZeroDivisionError:
print("ZeroDivisionError: Cannot divide by 0")
except ValueError:
print("ValueError: Can only divide numerical value")
# except KeyboardInterrupt:
# print("KeyboardInterrupt: Execution interrupted by user")
except Exception as e: # catch all subclasses of Exception
print("Caught some other Exception:", e.__class__.__name__)
except BaseException as be: # catch all subclasses of BaseException
print("Caught a system-level exception:", be.__class__.__name__)
else:
print("No exceptions were found")
finally:
print("Goodbye")
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «How To Handle Exceptions (3 Min) In Python | Learn Error & Exception Handling», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.