An Exception is an error that occurs whenever there is something wrong with the code one writes or if there’s something wrong with the system one is working on. Usually we can identify an exception when a program crashes (stops working horribly, no programmer likes to see that) and in order to avoid that, we can write our program inside a try-except block.
This means that we are preparing our program to handle any error that may occur so instead of a horrible crash, you will get a simple message letting you know what happened.
The try-block is where you write the code that may cause an exception while the except-block is where we write the exception handling logic.
The Task:
Read a string, S, and print its integer value; if S cannot be converted to an integer, print Bad String.
S = input().strip()
try:
int_s = int(S)
print(int_s)
except:
print('Bad String')
'''
Sample Input 0
3
Sample Output 0
3
Sample Input 1
za
Sample Output 1
Bad String
'''
Top comments (0)