Featured
- Get link
- X
- Other Apps
Exception handling
Programming is full of errors and exception. Errors are caused by the mistakes in the program. If you coded along while reading and experimented around a little bit.you may have encountered one or two error message
They terminate our script and crash the program if they are not handled properly. There are 3 types of error
1) Syntax error
2) Runtime error
3) Logical error
->Syntax error can be rectified when compiler throws error
-> runtime error occurs during the program is running
->the program get executed but the output is not desired one
There are some more exception lets look into it:
IndentationError- raise when indentation is not specified properly
IndexError- raise when an index is not found in a sequence
NameError- raised when an identifier is not found in the local or global namespace
ZeroDivisionError- raised when division by zero takes place
KeyError- raised when specified key is not found in the dictionary
ValueError- raised when the built-in function for a data type has the valid type of arguments, but the argument have invalid value specified
Also there are some error which we will look in future post
Handling Exception:
The try and except statement are used to handle the runtime error.
Try: line of code that might encounter error
Except: line of code that will be executed when error occurs
print(10/0)
text = "hello"
number = int(text)
except ValueError:
print(" valueError...")
except ZeroDivisionError:
print("zero division error or code")
except:
Print("other exception")
In the try block we put the code we want to execute. We calculate these are some errors going to occur so we put that error in except block. The except block tell our script what to do when respective error occurs. We provide code that handle the situation.we can also use else statement for multiple except block
print(10/0)
except:
print("error")
except:
print("zero division error")
else:
print("everything ok")
In above block if there is error it shows error message else is shows everything ok
Finally statement:
These are the codes written inside a finally block which will be executed at last no matter what happens. These codes will also executed even if exception unhandled
Example:
print("hello")
x=10/0
except ZeroDivisionError:
print("zero division error")
finally:
print("have a great day")
Output:
zero division error
have a great day
- Get link
- X
- Other Apps






Comments
Post a Comment