0% found this document useful (0 votes)
2 views

Exception Handling in Python

The document provides an overview of exception handling in Python, detailing common exceptions and their descriptions, along with the syntax for handling exceptions using try, except, finally, and else blocks. It includes practical examples for handling multiple exceptions, counting vowels in a name, validating names, and checking for palindromes in a list. Additionally, it presents problem statements with input and output formats for various coding tasks related to exception handling.

Uploaded by

sattysr3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Exception Handling in Python

The document provides an overview of exception handling in Python, detailing common exceptions and their descriptions, along with the syntax for handling exceptions using try, except, finally, and else blocks. It includes practical examples for handling multiple exceptions, counting vowels in a name, validating names, and checking for palindromes in a list. Additionally, it presents problem statements with input and output formats for various coding tasks related to exception handling.

Uploaded by

sattysr3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Exception Handling in Python

What is an Exception?
An exception is an error that occurs during the execution of a
program. When Python encounters an error, it raises an
exception and stops executing the program, unless the
exception is handled.
11
Common Exceptions in Python
Exception Description
ZeroDivisionError Dividing by zero
ValueError Wrong value type
Operation on
TypeError
incompatible types
IndexError Index out of range
KeyError Missing dictionary key
FileNotFoundError File not found
NameError Variable not defined

Basic Syntax of Exception Handling


try:
# Code that might raise an exception
except ExceptionType:
# Code that runs if exception occurs
Example:
try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("You can't divide by zero.")

Multiple Except Blocks


try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
print("Result:", a / b)
except ZeroDivisionError:
print(" You can't divide by zero!")
except ValueError:
print(" Invalid input! Please enter a number.")

Finally Block
try:
x=1/0
except ZeroDivisionError:
print("Handled division by zero")
finally:
print("This always runs")

Else Block
try:
print("No error here!")
except:
print("An error occurred")
else:
print("Code ran successfully")
finally:
print("Cleanup done")

Catching Multiple Exceptions Together


try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print("Result:", a / b)
except (ZeroDivisionError, ValueError):
print("Error: Either invalid number or divide by zero.")

Count Vowels in Name


Problem Statement:
Write a function count_vowels(name) that returns the
number of vowels (a, e, i, o, u) in a given name.
________________________________________
Input Format:
• One line: Name (string)
Output Format:
• Print the number of vowels in the name
Constraints:
• Name contains only alphabetic characters

Test Cases:
Test Case 1:
Alice
Output: 3
Test Case 2:
Bob
Output: 1
Test Case 3:
Charlie
Output: 3
Test Case 4:
Jonathan
Output: 3
Test Case 5:
Zzz
Output: 0
Test Case 6:
aeiou

Handle Division by Zero


Problem Statement:
You are given T test cases. Each test case contains two
integers a and b. Print the result of a / b. If division by zero
occurs, print "Error".
Input Format:
• First line: Integer T — number of test cases
• Next T lines: Two integers a and b separated by space
Output Format:
• For each test case, print the result or "Error" if b is zero

Constraints:
• -1000 ≤ a, b ≤ 1000

Test Cases:
Test Case 1:
3
10 2
60
93
Output:
5.0
Error
3.0
Test Case 2:
1
100 0
Output: Error
Test Case 3:
1
25 5
Output: 5.0

Test Case 4:
2
-8 2
0 10
Output:
-4.0
0.0
Test Case 5:
2
70
33
Output:
Error
1.0
Test Case 6:
1
11
Output: 1.0

Name Validator
Problem Statement:
Write a function validate_names(names) that checks if each
name contains only alphabetic characters. If a name is
invalid, raise a ValueError and catch it to print "Invalid name:
<name>". Otherwise, print "Valid name: <name>".
Input Format:
• First line: Integer N — number of names
• Next N lines: One name per line
Output Format:
• For valid names, print: Valid name: <name>
• For invalid names, print: Invalid name: <name>
Constraints:
• Names should only contain alphabet letters
• Use isalpha() and exception handling

Test Cases:
Test Case 1:
4
Alice
Bob123
Charlie
@David
Output:
Valid name: Alice
Invalid name: Bob123
Valid name: Charlie
Invalid name: @David

Test Case 2:
2
Emma
Owen!
Output:
Valid name: Emma
Invalid name: Owen!

Test Case 3:
3
John
123
Kate
Output:
Valid name: John
Invalid name: 123
Valid name: Kate
Test Case 4:
1
Lily
Output:
Valid name: Lily
Test Case 5:
2
A1ice
B0b
Output:
Invalid name: A1ice
Invalid name: B0b

Test Case 6:
3
Mike
Leo
Zara123
Output:
Valid name: Mike
Valid name: Leo
Invalid name: Zara123
Check Palindromes in a List
Problem Statement:
Write a function get_palindromes(words) that takes a list of
words and returns a list of all palindromes (words that read
the same backward and forward). A palindrome should be
case-sensitive.

Input Format:
• First line: Integer N — number of words
• Next N lines: One word per line
Output Format:
• Print each palindrome on a new line

Constraints:
• Each word is a non-empty string without spaces
• Case-sensitive check (e.g., "Madam" is not equal to
"madam")

Test Cases:
Test Case 1:
4
madam
apple
noon
hello
Output:
madam
noon
Test Case 2:
3
racecar
car
civic
Output:
racecar
civic
Test Case 3:
2
level
LEVEL
Output:
level
Test Case 4:
1
wow
Output:
wow
Test Case 5:
5
refer
deed
noon
Radar
rotor
Output:
refer
deed
noon
rotor

You might also like