Your problem is before your try, here a, b = map(int, input().split())

The $ is given to int, this fails and raise the invalid literal for int() with base 10: $ which is pretty explicit

try:
    a, b = map(int, input().split())
    print(a//b)
except ZeroDivisionError as e:
    print('Enter code: ', e)
except ValueError as e:
    print('Enter code: ', e)
Answer from azro on Stack Overflow
๐ŸŒ
techPiezo
techpiezo.com โ€บ python โ€บ valueerror-in-python
ValueError in Python โ€“ techPiezo
July 8, 2022 - One of such mathematical operation could be finding the factorial of number. In Python, we need to first import the math module. ... But, same canโ€™t be said for value (-10.2). Because, then it would throw TypeError. Try it as well โ€“ ... Example II. ValueError also occurs when we provide too many values to unpack โ€“
Discussions

Python Basics: Raising Value Error
Python Development Techdegree Student 2,536 Points ... I've made a function that creates brand new product names using "artificial intelligence". I have a problem though, people keep on adding product ideas that are too short. It makes the suggestions look bad. Can you please raise a ValueError if ... More on teamtreehouse.com
๐ŸŒ teamtreehouse.com
3
March 9, 2021
Manually raising (throwing) an exception in Python - Stack Overflow
For example: try: some_code_that_may_raise_our_value_error() except ValueError as err: print(err.args) ... In Python 2.5, an actual message attribute was added to BaseException in favor of encouraging users to subclass Exceptions and stop using args, but the introduction of message and the ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
my input function is giving traceback and valueError-python - Stack Overflow
I have asked the user for input and set out while true,try and expect blocks. I keep getting valueError even though I have set out that integer required should be displayed if I enter a letter. More on stackoverflow.com
๐ŸŒ stackoverflow.com
I need help on how to raise a value error
If it is, raise a ValueError. ... Try adjusting your code to match this logical sequence. ... Thing 1: I suggest reading this article about how to find the length of a string object in Python. More on teamtreehouse.com
๐ŸŒ teamtreehouse.com
1
February 10, 2024
๐ŸŒ
Team Treehouse
teamtreehouse.com โ€บ community โ€บ catching-a-value-error
Catching a value error (Example) | Treehouse Community
September 19, 2017 - try: num = add(input("Enter number A: "), input("Enter number B: ")) except ValueError: return None else: return num
๐ŸŒ
Team Treehouse
teamtreehouse.com โ€บ community โ€บ python-basics-raising-value-error
Python Basics: Raising Value Error (Example) | Treehouse Community
March 9, 2021 - def suggest(product_idea): if len(product_idea) < 3: raise ValueError() return product_idea + "inatorโ€ ยท Hope that helps. Python Development Techdegree Student 2,536 Points
๐ŸŒ
MangoHost
mangohost.net โ€บ mangohost blog โ€บ python valueerror โ€“ exception handling with examples
Python ValueError โ€“ Exception Handling With Examples
August 3, 2025 - ... # Example of ValueError occurring naturally try: number = int("not_a_number") except ValueError as e: print(f"ValueError caught: {e}") # Output: ValueError caught: invalid literal for int() with base 10: 'not_a_number' # Another common scenario ...
๐ŸŒ
Turing
turing.com โ€บ kb โ€บ valueerror-in-python-and-how-to-fix
What is ValueError in Python & How to fix it
Example-1: Handle the ValueError for incorrect data ยท The script below should be placed in a Python file to collect the user's age value. The try block will throw the ValueError exception and output the custom error message if the user enters a non-numeric value for the age field.
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ errors-and-exceptions-in-python
Errors and Exceptions in Python - GeeksforGeeks
1 month ago - Python stops and points out the issue before running the program. Example 1: In this example, this code returns a syntax error because there is a missing colon (:) after the if statement.
๐ŸŒ
EyeHunts
tutorial.eyehunts.com โ€บ home โ€บ python valueerror exception
Python ValueError exception
March 2, 2023 - import math x = -100 try: math.sqrt(x) except ValueError: print(f'You entered {x}, which is not a positive number.') Output: You entered -100, which is not a positive number. Do comment if you have any doubts or suggestions on this Python exception-handling topic. ... All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-handle-valueerror-when-converting-values-in-python-417776
How to handle ValueError when converting values in Python | LabEx
Trying to unpack an iterable with the wrong number of elements: For example, a, b = [1, 2, 3] will raise a ValueError because the number of variables on the left-hand side does not match the number of elements in the list.
๐ŸŒ
Readthedocs
howtothink.readthedocs.io โ€บ en โ€บ latest โ€บ PvL_E.html
Exceptions โ€” How to Think Like a Computer Scientist: Learning with Python 3
If the function that called get_age (or its caller, or their caller, โ€ฆ) handles the error, then the program can carry on running; otherwise, Python prints the traceback and exits: >>> get_age() Please enter your age: 42 42 >>> get_age() Please enter your age: -2 Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "learn_exceptions.py", line 4, in get_age raise ValueError("{0} is not a valid age".format(age)) ValueError: -2 is not a valid age
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ exceptions.html
Built-in Exceptions โ€” Python 3.14.4 documentation
>>> class MyGroup(ExceptionGroup): ... def derive(self, excs): ... return MyGroup(self.message, excs) ... >>> e = MyGroup("eg", [ValueError(1), TypeError(2)]) >>> e.add_note("a note") >>> e.__context__ = Exception("context") >>> e.__cause__ ...
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-manage-valueerror-in-python-417443
How to manage ValueError in Python | LabEx
In this example, the code first attempts to convert the user's input to an integer, and then performs a division operation. If a ValueError is raised during the integer conversion, the first except block handles it.
Top answer
1 of 11
4326

How do I manually throw/raise an exception in Python?

Use the most specific Exception constructor that semantically fits your issue.

Be specific in your message, e.g.:

raise ValueError('A very specific bad thing happened.')

Don't raise generic exceptions

Avoid raising a generic Exception. To catch it, you'll have to catch all other more specific exceptions that subclass it.

Problem 1: Hiding bugs

raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.

For example:

def demo_bad_catch():
    try:
        raise ValueError('Represents a hidden bug, do not catch this')
        raise Exception('This is the exception you expect to handle')
    except Exception as error:
        print('Caught this error: ' + repr(error))

>>> demo_bad_catch()
Caught this error: ValueError('Represents a hidden bug, do not catch this',)

Problem 2: Won't catch

And more specific catches won't catch the general exception:

def demo_no_catch():
    try:
        raise Exception('general exceptions not caught by specific handling')
    except ValueError as e:
        print('we will not catch exception: Exception')
 

>>> demo_no_catch()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in demo_no_catch
Exception: general exceptions not caught by specific handling

Best Practices: raise statement

Instead, use the most specific Exception constructor that semantically fits your issue.

raise ValueError('A very specific bad thing happened')

which also handily allows an arbitrary number of arguments to be passed to the constructor:

raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz') 

These arguments are accessed by the args attribute on the Exception object. For example:

try:
    some_code_that_may_raise_our_value_error()
except ValueError as err:
    print(err.args)

prints

('message', 'foo', 'bar', 'baz')    

In Python 2.5, an actual message attribute was added to BaseException in favor of encouraging users to subclass Exceptions and stop using args, but the introduction of message and the original deprecation of args has been retracted.

Best Practices: except clause

When inside an except clause, you might want to, for example, log that a specific type of error happened, and then re-raise. The best way to do this while preserving the stack trace is to use a bare raise statement. For example:

logger = logging.getLogger(__name__)

try:
    do_something_in_app_that_breaks_easily()
except AppError as error:
    logger.error(error)
    raise                 # just this!
    # raise AppError      # Don't do this, you'll lose the stack trace!

Don't modify your errors... but if you insist.

You can preserve the stacktrace (and error value) with sys.exc_info(), but this is way more error prone and has compatibility problems between Python 2 and 3, prefer to use a bare raise to re-raise.

To explain - the sys.exc_info() returns the type, value, and traceback.

type, value, traceback = sys.exc_info()

This is the syntax in Python 2 - note this is not compatible with Python 3:

raise AppError, error, sys.exc_info()[2] # avoid this.
# Equivalently, as error *is* the second object:
raise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]

If you want to, you can modify what happens with your new raise - e.g. setting new args for the instance:

def error():
    raise ValueError('oops!')

def catch_error_modify_message():
    try:
        error()
    except ValueError:
        error_type, error_instance, traceback = sys.exc_info()
        error_instance.args = (error_instance.args[0] + ' <modification>',)
        raise error_type, error_instance, traceback

And we have preserved the whole traceback while modifying the args. Note that this is not a best practice and it is invalid syntax in Python 3 (making keeping compatibility much harder to work around).

>>> catch_error_modify_message()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in catch_error_modify_message
  File "<stdin>", line 2, in error
ValueError: oops! <modification>

In Python 3:

raise error.with_traceback(sys.exc_info()[2])

Again: avoid manually manipulating tracebacks. It's less efficient and more error prone. And if you're using threading and sys.exc_info you may even get the wrong traceback (especially if you're using exception handling for control flow - which I'd personally tend to avoid.)

Python 3, Exception chaining

In Python 3, you can chain Exceptions, which preserve tracebacks:

raise RuntimeError('specific message') from error

Be aware:

  • this does allow changing the error type raised, and
  • this is not compatible with Python 2.

Deprecated Methods:

These can easily hide and even get into production code. You want to raise an exception, and doing them will raise an exception, but not the one intended!

Valid in Python 2, but not in Python 3 is the following:

raise ValueError, 'message' # Don't do this, it's deprecated!

Only valid in much older versions of Python (2.4 and lower), you may still see people raising strings:

raise 'message' # really really wrong. don't do this.

In all modern versions, this will actually raise a TypeError, because you're not raising a BaseException type. If you're not checking for the right exception and don't have a reviewer that's aware of the issue, it could get into production.

Example Usage

I raise Exceptions to warn consumers of my API if they're using it incorrectly:

def api_func(foo):
    '''foo should be either 'baz' or 'bar'. returns something very useful.'''
    if foo not in _ALLOWED_ARGS:
        raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo)))

Create your own error types when apropos

"I want to make an error on purpose, so that it would go into the except"

You can create your own error types, if you want to indicate something specific is wrong with your application, just subclass the appropriate point in the exception hierarchy:

class MyAppLookupError(LookupError):
    '''raise this when there's a lookup error for my app'''

and usage:

if important_key not in resource_dict and not ok_to_be_missing:
    raise MyAppLookupError('resource is missing, and that is not ok.')
2 of 11
579

Don't do this. Raising a bare Exception is absolutely not the right thing to do; see Aaron Hall's excellent answer instead.

It can't get much more Pythonic than this:

raise Exception("I know Python!")

Replace Exception with the specific type of exception you want to throw.

See the raise statement documentation for Python if you'd like more information.

๐ŸŒ
EDUCBA
educba.com โ€บ home โ€บ software development โ€บ software development tutorials โ€บ python tutorial โ€บ python valueerror
Python ValueError | How to Avoid ValueError in Python with Examples
May 13, 2024 - In any case, if the quantity of ... to unload in Python will be tossed by Python. For example, envision you have a dog, and you attempt to place it in a fish tank....
Call ย  +917738666252
Address ย  Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
Top answer
1 of 2
1

You are not including all your code as you describe it. Input section should look like this:

while True:
    try:   
        pass_credit=int(input("please enter your credits at pass:"))
        break
    except ValueError as e:
        print ("Bad integer value entered, try again.")

while True:
    try:   
        defer_credit=int(input("please enter your credits at defer:"))
        break
    except ValueError as e:
        print ("Bad integer value entered, try again.")

while True:
    try:   
        fail_credit=int(input("please enter your credits at fail:"))
        break
    except ValueError as e:
        print ("Bad integer value entered, try again.")

print(f"You entered: {pass_credit=}, {defer_credit=}, {fail_credit=}")

In fact, it would be better to capture the value before conversion to provide a better error message, e.g.:

while True:
    try:   
        entry=input("please enter your credits at pass:")
        pass_credit = int(entry)
        break
    except ValueError as e:
        print (f"You entered: {entry}, which is not an integer, try again.")

You stated that you used while and try..except. What did you miss? Comment please.

2 of 2
0

I ran the same code in Python IDLE and its working perfectly fine.

just check if you have some modules which you have imported in the same file. Also Check by running the same code after

if __name__ =='__main__':
    pass_credit=int(float(input("please enter your credits at pass:")))
    defer_credit=int(float(input("Please enter your credits at defer:")))
    fail_credit=int(float(input("please enter your credits at fail:")))

What is the input numbers that you are giving , is it like 10K for 10000. As 10k by default will be considered string. Since your error mentions of 'k' or does the input have decimal numbers?

๐ŸŒ
Team Treehouse
teamtreehouse.com โ€บ community โ€บ i-need-help-on-how-to-raise-a-value-error
I need help on how to raise a value error (Example) | Treehouse Community
February 10, 2024 - Thing 3: Check out how to use if statements in Python. If the length of product_idea is less than 3, you want to raise a ValueError. But if this isn't the case, you want to return product_idea + "inator".
๐ŸŒ
Medium
medium.com โ€บ @infotechdreamer โ€บ valueerror-in-python-what-it-is-how-to-fix-63251108438c
ValueError in Python: What it is & How To Fix? | by Infotechdreamer | Medium
July 25, 2023 - A function might expect a string in a specific format, such as a date or time in a certain format, but receives a string that does not match the expected format. This can cause a ValueError if the function is not able to parse the input string.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-fix-valueerror-exceptions-in-python
How To Fix Valueerror Exceptions In Python - GeeksforGeeks
July 23, 2025 - Below, code attempts to convert a numeric value (`a`) and a non-numeric string (`b`) to floats using the `float()` function. A try-except block is used to catch a potential `ValueError` that may occur during the conversion of the non-numeric string.