Skip to content

Commit 4035a3f

Browse files
committed
Added Exception handling topic.
Signed-off-by: Amol Kahat <akahat@redhat.com>
1 parent 5977635 commit 4035a3f

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

‎main_book.pdf‎

2.34 KB
Binary file not shown.

‎main_book.tex‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -833,15 +833,21 @@ \subsection{*args and **kwargs in Function}
833833
\section{Decorators}
834834
835835
\section{Exception Handling}
836+
In Python there are multiple built in exceptions are present. Exceptions are designed to handle the error in running program. Consider if you are converting the strings to the integer, which is against the Python programming language rule. To handle this situation exceptions are used. If exceptions are not used then program will crash.
837+
\paragraph{}
838+
In Python exceptions are defined using \texttt{try},\texttt{except}, \texttt{finally} and \texttt{else} keywords. In the \texttt{try} block you can write your code, if you know that this will cause an error then you can write that in to the \texttt{try} block. To handle the error you can write your error message in to the \texttt{except} block.
839+
\paragraph{}
840+
Once error occur in \texttt{try} block then control passes to the \texttt{except} block and continues the program execution.
836841
\begin{lstlisting}
837842
try:
838843
int("abc")
839844
except:
840845
print("Error occured")
841846
842847
print("Hello")
843-
844848
\end{lstlisting}
849+
850+
Let's consider the another example, If you want use should insert proper integer value then you should write it using following way. This program will run until user will not provide the integer value.
845851
\begin{lstlisting}
846852
while True:
847853
val = input("Enter Value: ")
@@ -861,6 +867,8 @@ \section{Exception Handling}
861867
Enter Value: 123
862868
Hello
863869
\end{lstlisting}
870+
871+
In Python multiple exceptions are present, those exception are used with specific conditions, You will use \texttt{ValueError} exception when convert the string value to integer.
864872
\begin{lstlisting}
865873
d = {1:'abc'}
866874
@@ -874,6 +882,21 @@ \section{Exception Handling}
874882
print("Invalid value inserted.")
875883
except KeyError:
876884
print("Key is not available in dict")
885+
886+
print("Hello")
887+
\end{lstlisting}
888+
In above program if you provide another value expect digits then you will get value error. If you provide the any digit except 1 then it will throw an key error.
889+
890+
Exception is generic class, if you don't know which error will occur then you will write Exception class and print it.
891+
\begin{lstlisting}
892+
d = {1:'abc'}
893+
894+
while True:
895+
val = input("Enter Value: ")
896+
try:
897+
int(val)
898+
d[int(val)]
899+
break
877900
except Exception as e:
878901
print(e)
879902
print("Error occured")

0 commit comments

Comments
 (0)