简体   繁体   English

PHP尝试捕获一些问题

[英]PHP try-catch some problems

Hello. 你好。 Is it possible to use such code in PHP ? 是否可以在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. 仅当将异常抛出到try块中时,才会捕获它们。 Exceptions thrown in catch blocks are not caught within other sibling catch blocks of the same try..catch statement. catch块中引发的异常不会在同一try..catch语句的其他同级catch块中catch You have to nest the whole thing in another outer try..catch block to catch those. 您必须将整个东西嵌套在另一个外部try..catch块中才能捕获它们。

Nest multiple try...catch instead. 嵌套多个try...catch代替。

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 参见PHP:异常-手册

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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