Skip to content

Commit 71b1899

Browse files
authored
Merge pull request #34 from cipherhacker/master
Error handling . close #29
2 parents cfbc50a + 995a802 commit 71b1899

File tree

2 files changed

+177
-1
lines changed

2 files changed

+177
-1
lines changed

python/13-Error_Handling.md

+176
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
<h1 align="center"> Error Handling </h1>
2+
3+
4+
## Exceptions
5+
6+
>Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. **Errors detected during execution are called exceptions**
7+
8+
#### Some examples :
9+
10+
1.You ask for an integer but input value of other datatype
11+
```python
12+
>>> n = int(input("Please enter a number: "))
13+
Please enter a number: 23.5
14+
15+
Traceback (most recent call last):
16+
File "<stdin>", line 1, in <module>
17+
ValueError: invalid literal for int() with base 10: '23.5'
18+
```
19+
20+
2.The famous divide by zero exception
21+
```python
22+
>>> 10 * (1/0)
23+
24+
Traceback (most recent call last):
25+
File "<stdin>", line 1, in <module>
26+
ZeroDivisionError: division by zero
27+
```
28+
29+
3.Using undeclared variable
30+
```python
31+
>>> 4 + spam*3
32+
33+
Traceback (most recent call last):
34+
File "<stdin>", line 1, in <module>
35+
NameError: name 'spam' is not defined
36+
```
37+
38+
4.Concatenation of string and integer doesn't work in python.
39+
```python
40+
>>> '2' + 2
41+
42+
Traceback (most recent call last):
43+
File "<stdin>", line 1, in <module>
44+
TypeError: Can't convert 'int' object to str implicitly
45+
```
46+
You can handle this situation by doing this
47+
```python
48+
'2'+str(2)
49+
```
50+
51+
## Catching the notorious exceptions
52+
53+
>Exceptions handling in Python is very similar to Java. The code, which harbours the risk of an exception, is embedded in a try block. But whereas in Java exceptions are caught by catch clauses, we have statements introduced by an "except" keyword in Python.
54+
55+
As we saw an exception above where the user was entering a wrong datatype . With the aid of exception handling, we can write robust code for reading an integer from input:
56+
57+
```python
58+
while True:
59+
try:
60+
n = input("Please enter an integer: ")
61+
n = int(n)
62+
break
63+
except ValueError:
64+
print("No valid integer! Please try again ...")
65+
print("Great, you successfully entered an integer!")
66+
```
67+
68+
It's a loop, which breaks only, if a valid integer has been given. It works like this :
69+
>The while loop is entered. The code within the try clause will be executed statement by statement. If no exception occurs during the execution, the execution will reach the break statement and the while loop will be left. If an exception occurs, i.e. in the casting of n, the rest of the try block will be skipped and the except clause will be executed. The raised error, in our case a ValueError, has to match one of the names after except. In our example only one, i.e. "ValueError:". After having printed the text of the print statement, the execution does another loop. It starts with a new input().
70+
71+
>A try statement may have more than one except clause for different exceptions. But at most one except clause will be executed with different types of exceptions such as :
72+
73+
* ArithmeticError
74+
* IOError
75+
* ValueError
76+
77+
>You can even have more than one type of exception caught in a single except like this:
78+
```python
79+
except (IOError, ValueError):
80+
```
81+
82+
83+
## Rise of the Exceptions
84+
85+
>Python allows you to raise an exception by yourself .
86+
87+
>The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception). If an exception class is passed, it will be implicitly instantiated by calling its constructor with no arguments:
88+
89+
```python
90+
raise ValueError # shorthand for 'raise ValueError()'
91+
```
92+
>If you need to determine whether an exception was raised but don’t intend to handle it, a simpler form of the raise statement allows you to re-raise the exception:
93+
94+
```python
95+
>>> try:
96+
... raise NameError('HiThere')
97+
... except NameError:
98+
... print('An exception flew by!')
99+
... raise
100+
...
101+
An exception flew by!
102+
Traceback (most recent call last):
103+
File "<stdin>", line 2, in <module>
104+
NameError: HiThere
105+
```
106+
If no expressions are present, raise re-raises the last exception that was active in the current scope. If no exception is active in the current scope, a RuntimeError exception is raised indicating that this is an error.
107+
108+
## Creator of the Exceptions
109+
110+
Just like khaleesi , You can be the creator yourself. Just the story is changed a little bit , here you create exceptions... Get ready to become the mother of exceptions
111+
112+
>Programs may name their own exceptions by creating a new exception class. **Exceptions should typically be derived from the Exception class, either directly or indirectly**.
113+
114+
```python
115+
# A python program to create user-defined exception
116+
117+
# class MyError is derived from super class Exception
118+
class MyError(Exception):
119+
120+
# Constructor or Initializer
121+
def __init__(self, value):
122+
self.value = value
123+
124+
# __str__ is to print() the value
125+
def __str__(self):
126+
return(repr(self.value))
127+
128+
try:
129+
raise(MyError(3*2))
130+
131+
# Value of Exception is stored in error
132+
except MyError as error:
133+
print('A New Exception occured with value: '+str(error.value))
134+
```
135+
136+
Output:
137+
```python
138+
A New Exception occured with value: 6
139+
```
140+
141+
142+
143+
## Defining clean-up actions(Roke tujhko aandhiyan ya zameen aur aasman Paayega jo lakshya hai tera)
144+
145+
As the title suggest :P , we will be defining a block of code which will run whether an exception occurs or not.
146+
147+
>The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example:
148+
149+
```python
150+
>>> try:
151+
... raise KeyboardInterrupt
152+
... finally:
153+
... print('Goodbye, world!')
154+
...
155+
156+
157+
Goodbye, world!
158+
KeyboardInterrupt
159+
Traceback (most recent call last):
160+
File "<stdin>", line 2, in <module>
161+
```
162+
163+
## what **_else_**
164+
165+
>The try ... except statement has an optional else clause. An else block has to be positioned after all the except clauses. An else clause will be executed if the try clause doesn't raise an exception.
166+
167+
```python
168+
>>> try:
169+
... sambha_kitne_aadmi_the = 'ek huzoor'
170+
... else:
171+
... print('Your code is good to go :D')
172+
...
173+
174+
175+
Your code is good to go :D
176+
```

python/readme.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,4 @@
1515
10. [User defined functions](./10-user_defined_functions.md)
1616
11. [Lambda](./11-Lambda.md)
1717
12. [Modules](./12-Modules.md)
18-
13. [Error Handling]()
18+
13. [Error Handling](./13-Error_Handling.md)

0 commit comments

Comments
 (0)