Exceptions¶
pywhatwgurl raises standard Python exceptions for error handling.
ValueError¶
Raised when URL parsing fails due to an invalid URL:
from pywhatwgurl import URL
try:
url = URL("not-a-valid-url")
except ValueError as e:
print(f"Failed to parse URL: {e}")
Common Causes¶
- Missing or invalid scheme
- Invalid characters in hostname
- Malformed IPv6 address
- Invalid port number
TypeError¶
Raised when URLSearchParams is initialized with invalid data:
from pywhatwgurl import URLSearchParams
try:
# List elements must be 2-element sequences
params = URLSearchParams([("key",)]) # Missing value
except TypeError as e:
print(f"Invalid initialization: {e}")
KeyError¶
Raised when accessing a non-existent key in URLSearchParams:
from pywhatwgurl import URLSearchParams
params = URLSearchParams("foo=1")
try:
value = params["nonexistent"] # Raises KeyError
except KeyError:
print("Key not found")
# To avoid KeyError, use .get() which returns None
value = params.get("nonexistent") # Returns None
Examples¶
Invalid Scheme¶
from pywhatwgurl import URL
try:
URL("://missing-scheme.com")
except ValueError:
print("URL must have a valid scheme")
Invalid Host¶
Invalid Port¶
Error Handling Best Practices¶
Use URL.parse() for Safe Parsing¶
The URL.parse() static method returns None instead of raising an exception:
from pywhatwgurl import URL
# Returns None if invalid, never raises
url = URL.parse(user_input)
if url is None:
print("Please enter a valid URL")
else:
print(f"Valid URL: {url.href}")
Use URL.can_parse() to Validate¶
Check if a URL can be parsed without actually parsing it:
from pywhatwgurl import URL
if URL.can_parse(user_input):
url = URL(user_input) # Safe to parse
else:
print("Invalid URL format")