简体   繁体   中英

PHP try-catch some problems

Hello. Is it possible to use such code in PHP ?

try {
  throw new InternalException('Internal');
} catch (InternalException $e) {
  throw new Exception('Internal To global');
} catch (Exception $e){
  print $e->getMessage();
}

class InternalException extends Exception {
  // some code here
}

是的,您可以分别捕获特定的异常。

Exceptions are only caught if they're thrown in try blocks. Exceptions thrown in catch blocks are not caught within other sibling catch blocks of the same try..catch statement. You have to nest the whole thing in another outer try..catch block to catch those.

Nest multiple try...catch instead.

try {
    throw new InternalException('Internal');
} catch (InternalException $e) {
    try {
        throw new Exception('Internal To global');
    } catch (Exception $e){
        print $e->getMessage();
    }
}

class InternalException extends Exception {
  // some code here
}

See PHP: Exceptions - Manual

It does not make sense to "transform" Exceptions. Don't throw em if you won't handle them.

You can catch different Exceptions this way:

try {
    throw new InternalException();
} catch (HardwareException $e) {
} catch (InternalException $e) {
    // this catch block will be executed
} catch (Exception $e) {
    // all other exceptions
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM