CKTIS / PHP
ValueError
Identify a value of an acceptable type that the operation cannot use.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
catch (ValueError $failure) { /* handle invalid value */ }Identify a value of an acceptable type that the operation cannot use. Built-ins can raise ValueError for a forbidden range or option, whereas an incompatible argument type can raise TypeError. A program may also throw ValueError explicitly for its own domain constraints.
try { str_repeat("x",-1); } catch(ValueError $e){$bad=get_class($e);}
try { str_repeat([],2); } catch(TypeError $e){$wrong=get_class($e);}
echo json_encode([str_repeat("x",2),$bad,$wrong]);
["xx","ValueError","TypeError"]
Examples
<?php
try { str_repeat("x",-1); } catch(ValueError $e){$bad=get_class($e);}
try { str_repeat([],2); } catch(TypeError $e){$wrong=get_class($e);}
echo json_encode([str_repeat("x",2),$bad,$wrong]);
Result
["xx","ValueError","TypeError"]