Kevin
Kevin

Reputation: 83

Exceptions in PHP

So i'm trying to learn about exceptions. And i've come accross something people often do , but dont really explain why they do it and how it works. Maybe this is something that speaks for itself but I still dont get it, I apologize if this question might come over as a bad question.

Basically this is the code I'm working with:

catch(Exception $e) {
  echo 'Message: ' .$e->getMessage();
}

What is $e where is this variable defined. I have an idea.

What i'm thinking is that you're assigning the exception object to the variable $e but i'm not sure. Shouldnt it be catch (Exception = $e) ?

Upvotes: 0

Views: 51

Answers (3)

Guy Thouret
Guy Thouret

Reputation: 94

In this code

catch(Exception $e) {
  echo 'Message: ' .$e->getMessage();
}

The keyword Exception is the type for the parameter $e.

In PHP Exception is the base exception class that all exceptions derive from so that catch block is a catch-all for all exceptions.

i.e. You might want multiple handlers for different exception types before the catch-all:

try {
  someOperation($parameter);
} catch(DatabaseException $e) {
  echo 'Database Exception: ' .$e->getMessage();
} catch(Exception $e) {
  echo 'General Exception: ' .$e->getMessage();
}

Upvotes: 0

Andrea Golin
Andrea Golin

Reputation: 3559

Uhm, now that i think about it, i have always considered the Exception $e to be the input for the catch() call.

As far as i know, you are not defining $e, as it is already thrown, you are just passing it to the catch() block, as you would do with a function name($input){}

Upvotes: 0

deceze
deceze

Reputation: 521995

It works pretty much the same as function parameters:

function foo(Bar $bar) { ... }

You use a type hint Bar followed by the parameter name $bar, and that declares the variable.

In the case of try..catch, that declaration happens in catch:

catch (Exception $e) { ... }

This uses the type hint Exception, which here is used to specify which kinds of exceptions the catch is supposed to catch. You can limit the catch to specific kinds of exceptions and/or define multiple different catch blocks for different kinds of exceptions. The exception itself is then available in the variable $e. You can use any arbitrary variable name here, just as for function parameters.

Upvotes: 1

Related Questions