|
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "cell_type": "markdown", |
| 5 | + "metadata": {}, |
| 6 | + "source": [ |
| 7 | + "## Handling exceptions 💥🤯" |
| 8 | + ] |
| 9 | + }, |
| 10 | + { |
| 11 | + "cell_type": "markdown", |
| 12 | + "metadata": {}, |
| 13 | + "source": [ |
| 14 | + "### Custom exception, and `ValueError` for an input\n", |
| 15 | + "1. Design a new user-defined exception class.\n", |
| 16 | + "\n", |
| 17 | + "2. This class should handle the input value of a variable called salary.\n", |
| 18 | + "\n", |
| 19 | + "3. Ensure that the salary value is between 1000 and 2000.\n", |
| 20 | + "\n", |
| 21 | + "4. If the salary value is not within this range, raise an exception.\n", |
| 22 | + "\n", |
| 23 | + "5. The exception should indicate that the salary is not within the range of 1000 to 2000." |
| 24 | + ] |
| 25 | + }, |
| 26 | + { |
| 27 | + "cell_type": "code", |
| 28 | + "execution_count": 1, |
| 29 | + "metadata": {}, |
| 30 | + "outputs": [ |
| 31 | + { |
| 32 | + "name": "stdout", |
| 33 | + "output_type": "stream", |
| 34 | + "text": [ |
| 35 | + "The salary is 1000\n" |
| 36 | + ] |
| 37 | + } |
| 38 | + ], |
| 39 | + "source": [ |
| 40 | + "class SalaryNotInRange(Exception):\n", |
| 41 | + " def __init__(self, message=\"The salary must be between 1000 and 2000\"):\n", |
| 42 | + " self.__message = message\n", |
| 43 | + " super().__init__(self.__message)\n", |
| 44 | + " \n", |
| 45 | + "salary = None\n", |
| 46 | + "while True:\n", |
| 47 | + " try:\n", |
| 48 | + " input_salary = int(input(\"Enter a salary: \"))\n", |
| 49 | + " if input_salary not in range(1000,2001):\n", |
| 50 | + " raise SalaryNotInRange\n", |
| 51 | + " salary = input_salary\n", |
| 52 | + " break\n", |
| 53 | + " except SalaryNotInRange as e:\n", |
| 54 | + " print(e)\n", |
| 55 | + " except ValueError:\n", |
| 56 | + " print(\"The input salary must be an integer.\")\n", |
| 57 | + "print(f\"The salary is {salary}\")" |
| 58 | + ] |
| 59 | + }, |
| 60 | + { |
| 61 | + "cell_type": "markdown", |
| 62 | + "metadata": {}, |
| 63 | + "source": [ |
| 64 | + "### A virtual cart" |
| 65 | + ] |
| 66 | + }, |
| 67 | + { |
| 68 | + "cell_type": "markdown", |
| 69 | + "metadata": {}, |
| 70 | + "source": [] |
| 71 | + } |
| 72 | + ], |
| 73 | + "metadata": { |
| 74 | + "kernelspec": { |
| 75 | + "display_name": "Python 3", |
| 76 | + "language": "python", |
| 77 | + "name": "python3" |
| 78 | + }, |
| 79 | + "language_info": { |
| 80 | + "codemirror_mode": { |
| 81 | + "name": "ipython", |
| 82 | + "version": 3 |
| 83 | + }, |
| 84 | + "file_extension": ".py", |
| 85 | + "mimetype": "text/x-python", |
| 86 | + "name": "python", |
| 87 | + "nbconvert_exporter": "python", |
| 88 | + "pygments_lexer": "ipython3", |
| 89 | + "version": "3.9.6" |
| 90 | + } |
| 91 | + }, |
| 92 | + "nbformat": 4, |
| 93 | + "nbformat_minor": 2 |
| 94 | +} |
0 commit comments