Skip to content

Commit d829dda

Browse files
Introduce custom exception for handling negative numbers
1 parent 931add7 commit d829dda

File tree

3 files changed

+12
-6
lines changed

3 files changed

+12
-6
lines changed

src/coding_task/app.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
from coding_task.string_calculator import calculate_sum
1+
from coding_task.string_calculator import *
22

33

44
def run_app():
55
user_input = input("Enter delimited numbers to add: ")
66
try:
77
print("Total sum: ", calculate_sum(user_input))
8+
except NegativeNumbersNotSupportedException as ex:
9+
print("Error: Negative numbers are not supported!")
810
except Exception as ex:
911
print("An unexpected error occurred: ", str(ex))

src/coding_task/string_calculator.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,16 @@
22

33
SUPPORTED_DELIMITERS = r'[\s,;:\_]'
44
MAX_NUMBER = 100
5-
MESSAGE_NEGATIVE_NUMBERS_NOT_SUPPORTED = "Negative numbers are not supported!"
5+
6+
7+
class NegativeNumbersNotSupportedException(Exception):
8+
def __init__(self):
9+
pass
610

711

812
def __validate(number):
913
if number < 0:
10-
raise ValueError(MESSAGE_NEGATIVE_NUMBERS_NOT_SUPPORTED)
14+
raise NegativeNumbersNotSupportedException
1115
return number
1216

1317

test/test_string_calculator.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import pytest
22

33
from coding_task.string_calculator import calculate_sum
4+
from coding_task.string_calculator import NegativeNumbersNotSupportedException
45

56
test_cases_for_sum_calculation = [
67
("5", 5),
@@ -97,8 +98,7 @@ def test_ignore_numbers_over_100(input_string, expected):
9798

9899
def test_calculates_sum_should_throw_exception_when_negative_number_is_provided():
99100
"""
100-
Test 'calculate_sum()' to throw 'ValueError' exception when negative numbers provided
101+
Test 'calculate_sum()' to throw 'NegativeNumbersNotSupportedException' exception when negative numbers are provided
101102
"""
102-
with pytest.raises(ValueError) as exception:
103+
with pytest.raises(NegativeNumbersNotSupportedException):
103104
calculate_sum("1,2,-3")
104-
assert str(exception.value) == "Negative numbers are not supported!"

0 commit comments

Comments
 (0)