Shafizadeh Shafizadeh - 4 months ago 11
PHP Question

Can I use throw without any message?

Here is my code:

try {

if ( condition 1 ) {
throw;
} else {
// do something
}

// some code here

if ( condition 2 ){
throw;
}

} catch (Exception $e) {
echo "something is wrong";
}


As you see, my
catch
block has its own error message, And that message is a constant. So really I don't need to pass a message when I use
throw
like this:

throw new Exception('error message');


Well can I use
throw
without anything? I just need to jump into
catch
block.

Honestly writing an useless error message is annoying for me.




As you know my current code has a syntax error: (it referring to
throw;
)



Parse error: syntax error, unexpected ';' in {path}

Answer

message parameter is optional in the Exception constructor. So if you don't have/want to put - just don't:

throw new Exception;

But you still must throw an instance of the Exception class (or a class that extends it), since it is a part of the php language syntax.