{"id":48488,"date":"2025-12-30T10:26:52","date_gmt":"2025-12-30T10:26:52","guid":{"rendered":"https:\/\/www.carmatec.com\/?p=48488"},"modified":"2025-12-30T10:26:52","modified_gmt":"2025-12-30T10:26:52","slug":"python-raise-valueerror-guida-con-esempi","status":"publish","type":"post","link":"https:\/\/www.carmatec.com\/it_it\/blog\/python-raise-valueerro-guide-with-examples\/","title":{"rendered":"Python Raise ValueError: Guida completa con esempi"},"content":{"rendered":"<p>In Python, exceptions provide a structured way to handle errors and unexpected situations. Among the built-in exceptions, <code>ValueError<\/code> is one of the most frequently encountered. It is raised when a function or operation receives an argument that has the correct type but an inappropriate value.<\/p>\n<p>This is distinct from <code>TypeError<\/code>, which occurs when the argument is of the wrong type entirely. For example:<\/p>\n<ul>\n<li>Passing a string to a function expecting an integer raises <code>TypeError<\/code>.<\/li>\n<li>Passing a negative number to a function that requires a positive integer raises <code>ValueError<\/code>.<\/li>\n<\/ul>\n<p><code>ValueError<\/code> inherits directly from <code>Exception<\/code> in Python\u2019s exception hierarchy and is commonly triggered automatically by built-in functions in cases such as:<\/p>\n<ul>\n<li><code>int(\"abc\")<\/code> \u2014 attempting to convert a non-numeric string to an integer.<\/li>\n<li><code>float(\"nan\")<\/code> in certain contexts or invalid conversions.<\/li>\n<li>Unpacking mismatches like <code>a, b = [1]<\/code>.<\/li>\n<\/ul>\n<p>Manually raising <code>ValueError<\/code> is a best practice for input validation and enforcing domain constraints.<\/p>\n<h3><strong>When to Raise ValueError in Python<\/strong><\/h3>\n<p>Raise <code>ValueError<\/code> explicitly when:<\/p>\n<ul>\n<li>The input type is correct, but the value is semantically invalid.<\/li>\n<li>You need to enforce business rules or mathematical constraints (e.g., non-negative numbers, valid ranges).<\/li>\n<li>You want to signal that a value is out of an expected domain.<\/li>\n<\/ul>\n<h3><strong>Syntax for Raising ValueError in Python<\/strong><\/h3>\n<p>The basic syntax is straightforward:<\/p>\n<pre>python\r\nraise ValueError(\"Your descriptive error message here\")<\/pre>\n<p>You can omit the message (<code>raise ValueError<\/code>), but including a clear, specific message is strongly recommended for maintainability and debugging.<\/p>\n<h3><strong>Practical Examples for Python Raise ValueError<\/strong><\/h3>\n<h5><strong>1. Validating a Positive Integer<\/strong><\/h5>\n<pre>python\r\ndef set_temperature(temp):\r\n \u00a0\u00a0 if not isinstance(temp, (int, float)):\r\n \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 raise TypeError(\"Temperature must be a number\")\r\n \u00a0\u00a0 if temp &lt; -273.15:\r\n \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 raise ValueError(f\"Temperature below absolute zero is invalid: {temp}\")\r\n\r\nset_temperature(-300)\u00a0 # Raises ValueError<\/pre>\n<h5><strong>2. Ensuring Non-Negative Input for Square Root<\/strong><\/h5>\n<pre>python\r\nimport math\r\n\r\ndef safe_square_root(value):\r\n \u00a0\u00a0 if value &lt; 0:\r\n \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 raise ValueError(f\"Cannot take square root of negative number: {value}\")\r\n \u00a0\u00a0 return math.sqrt(value)\r\n\r\nsafe_square_root(-9)\u00a0 # Raises ValueError<\/pre>\n<h5><strong>3. Preventing Invalid Enum-Like Values<\/strong><\/h5>\n<pre>python\r\ndef set_status(status):\r\n \u00a0\u00a0 valid_statuses = {\"active\", \"inactive\", \"pending\"}\r\n \u00a0\u00a0 if status not in valid_statuses:\r\n \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 raise ValueError(f\"Invalid status: {status}. Must be one of {valid_statuses}\")\r\n\r\nset_status(\"banned\")\u00a0 # Raises ValueError<\/pre>\n<h5><strong>4. Custom Parsing with Validation<\/strong><\/h5>\n<pre>python\r\ndef parse_percentage(percentage_str):\r\n \u00a0\u00a0 try:\r\n \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 value = float(percentage_str.rstrip(\"%\"))\r\n \u00a0\u00a0 except ValueError:\r\n \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 raise ValueError(f\"Could not convert '{percentage_str}' to a number\")\r\n    if not 0 &lt;= value &lt;= 100:\r\n \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 raise ValueError(f\"Percentage must be between 0 and 100: got {value}\") \u00a0\u00a0\r\n \r\n\u00a0\u00a0 return value \/ 100\r\n\r\nparse_percentage(\"150%\")\u00a0 # Raises ValueError<\/pre>\n<h5><strong>5. Re-raising with Additional Context<\/strong><\/h5>\n<p>When wrapping another operation, you can preserve the original error using exception chaining:<\/p>\n<pre>python\r\ndef convert_to_int(input_str):\r\n \u00a0\u00a0 try:\r\n \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 return int(input_str)\r\n \u00a0\u00a0 except ValueError as exc:\r\n \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 raise ValueError(f\"Invalid integer format: '{input_str}'\") from exc<\/pre>\n<h5><strong>6. Catching and Handling ValueError<\/strong><\/h5>\n<pre>python\r\ntry:\r\n \u00a0\u00a0 set_temperature(-500)\r\nexcept ValueError as e:\r\n \u00a0\u00a0 print(f\"Validation error: {e}\")\r\n# Output: Validation error: Temperature below absolute zero is invalid: -500<\/pre>\n<h3><strong>Best Practices for Python Raise ValueError<\/strong><\/h3>\n<ol>\n<li><strong>Choose the Correct Exception<br \/>\n<\/strong>Use <code>ValueError<\/code> only for valid types with invalid values. Reserve <code>TypeError<\/code> for type mismatches.<\/li>\n<li><strong>Write Informative Messages<br \/>\n<\/strong>Include the actual value received and the expected constraint. This greatly aids debugging.<\/li>\n<li><strong>Validate Early<br \/>\n<\/strong>Check inputs at the beginning of functions to fail fast and avoid unnecessary computation.<\/li>\n<li><strong>Avoid Catching Broad Exceptions<br \/>\n<\/strong>Catch <code>ValueError<\/code> specifically rather than bare <code>except:<\/code> or <code>except Exception:<\/code> when possible.<\/li>\n<\/ol>\n<h2><strong>Conclusion<\/strong><\/h2>\n<p>Raising <code>ValueError<\/code> appropriately is a hallmark of clean, defensive Python programming. At <a href=\"https:\/\/www.carmatec.com\"><strong>Carmatec<\/strong><\/a>, our <a href=\"https:\/\/www.carmatec.com\/python-development-company\/\">Python development<\/a> team follows these best practices to build predictable, reliable, and maintainable applications. By validating inputs early and providing clear, meaningful error messages, we ensure our solutions are easier to debug, scale, and extend over time.<\/p>\n<p>This disciplined approach to exception handling improves code quality, reduces production issues, and enhances long-term system stability. When you <a href=\"https:\/\/www.carmatec.com\/hire-developers\/hire-python-developer\/\"><strong>hire Python developers<\/strong><\/a><strong> from Carmatec<\/strong>, you work with engineers who apply proven validation logic and industry-standard coding practices to deliver robust, enterprise-ready Python applications.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Python, exceptions provide a structured way to handle errors and unexpected situations. Among the built-in exceptions, ValueError is one of the most frequently encountered. It is raised when a function or operation receives an argument that has the correct type but an inappropriate value. This is distinct from TypeError, which occurs when the argument [&hellip;]<\/p>\n","protected":false},"author":10,"featured_media":48499,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4],"tags":[],"class_list":["post-48488","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog"],"_links":{"self":[{"href":"https:\/\/www.carmatec.com\/it_it\/wp-json\/wp\/v2\/posts\/48488","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.carmatec.com\/it_it\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.carmatec.com\/it_it\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.carmatec.com\/it_it\/wp-json\/wp\/v2\/users\/10"}],"replies":[{"embeddable":true,"href":"https:\/\/www.carmatec.com\/it_it\/wp-json\/wp\/v2\/comments?post=48488"}],"version-history":[{"count":0,"href":"https:\/\/www.carmatec.com\/it_it\/wp-json\/wp\/v2\/posts\/48488\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.carmatec.com\/it_it\/wp-json\/wp\/v2\/media\/48499"}],"wp:attachment":[{"href":"https:\/\/www.carmatec.com\/it_it\/wp-json\/wp\/v2\/media?parent=48488"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.carmatec.com\/it_it\/wp-json\/wp\/v2\/categories?post=48488"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.carmatec.com\/it_it\/wp-json\/wp\/v2\/tags?post=48488"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}