多个异常在一个尝试块中

问题描述:

如何一次尝试捕获多个邮件?多个异常在一个尝试块中

try{ 
    if (empty($news_genre)){ 
     throw new Exception('<div class="error">Error 1</div>'); 
    }elseif (strlen($news_title) < 30){ 
     throw new Exception('<div class="error">Error 2</div>'); 
    } elseif (strlen($news_image)< 30){ 
     throw new Exception('<div class="error">Error 3</div>'); 
    } elseif (strlen($news_description)< 500){ 
     throw new Exception('<div class="error">Error 4</div>'); 
    } elseif (count($news_tags) > 5){ 
     throw new Exception('<div class="error">Error 5</div>'); 
    } 
} catch (Exception $e) { 
    die ($e->getMessage()); 
} 

我想回应所有的错误在一行是这样的:

//die ($e->getMessage(), $e->getMessage(), $e->getMessage());  
<div class="error">Error 1</div> 
<div class="error">Error 2</div> 
<div class="error">Error 3</div> 
<div class="error">Error 4</div> 
<div class="error">Error 5</div> 

PS没有不同catch块!

+2

为什么?它不会超过第一个抛出的例外 – 2014-09-19 13:13:29

+0

我知道,这只是一个错误的例子。 – 2014-09-19 13:14:47

+0

这不是例外。这也不是如何工作的例外 – PeeHaa 2014-09-19 13:14:55

您不能捕捉多个例外,因为不能有多个例外。一旦抛出异常,代码块就会以该异常的状态退出。

如果你想创建一个验证错误列表,那么你不应该首先使用异常。 (不要为逻辑流程使用异常。)您应该检查逻辑并构建您的列表。在伪代码(因为我的PHP是足够生锈的是几乎不存在的):

if (someCondition()) { 
    // add error to array 
} 
if (anotherCondition()) { 
    // add another error to array 
} 
// etc. 

if (array has values) { 
    // display validation messages 
    // halt execution 
} 

(另请注意,我改变了你的else if结构到多个if S,因为逻辑上你也永远只能有一个消息与else if结构。)

您可以将消息存储在一个var中,并在执行if语句之一时引发异常。

try{ 
    $msg = false; 
    if (empty($news_genre)) 
     $msg .= '<div class="error">Error 1</div>'; 
    if (strlen($news_title) < 30) 
     $msg .= '<div class="error">Error 2</div>'; 
    if (strlen($news_image)< 30) 
     $msg .= '<div class="error">Error 3</div>'; 
    if (strlen($news_description)< 500) 
     $msg .= '<div class="error">Error 4</div>'; 
    if (count($news_tags) > 5) 
     $msg .= '<div class="error">Error 5</div>'; 
    if ($msg) 
     throw new Exception($msg); 
} catch (Exception $e) { 
    die ($e->getMessage()); 
} 
+0

不行,只抛出第一个。 – 2014-09-19 13:29:27

+0

@ user1791020你是否试过这段代码?你有没有看到我把'elseif'改成'if if'? – 2014-09-19 14:18:03