Using exception handling

I’ve just been playing around with exception handling for form processing

This works fine:

if(isset($_POST['submit'])) {
   
    
   $error = array();
   
   if(empty($_POST['title'])) {
    
    $error[] = "Opps, you forgot to give the article a title!";
    
   }
   
    if(empty($_POST['body'])) {
    
    $error[] = "Opps, you forgot to write the article!";
    
   }
   
   if($_POST['select'] === "choice") {
    
    $error[] = "Opps, you forgot to pick a category";
    
   }
   
   
   if(empty($_POST['publish']) && empty($_POST['not-publish'])) {
    
    $error[] = "Opps, you forgot to state whether you would like to publish the article or not!";
    
   }
   
   foreach($error as $error_message) {
    
    echo $error_message . br;
    
   }
   
}

But with exception handling it doesn’t do anything at all! What have I misunderstood about this OOP PHP code?

if(isset($_POST['submit'])) {
    
    try {
        
         if(empty($_POST['title'])) {
            
            throw new Exception("Opps, you forgot to give the article a title");
            
         }
         
         if(empty($_POST['body'])) {
            
            throw new Exception("Opps, you forgot to write the article!");
            
         }
         
         if($_POST['select'] === "choice") {
            
            throw new Exception("Opps, you forgot to pick a category!");
            
         }
         
         if(empty($_POST['publish']) && empty($_POST['not-publish'])) {
            
            throw new Exception("Opps, you forgot to pick a category!");
            
         }
         
         echo "Everything is working okay!";
        
    }
    
    catch (Exception $e) {
        
        $result = '<p>There has been a problem with the form</p>';
        $result .= br;
        $result .= '<p>' . $e->getMessage() . '</p>';
        
    }
    
}

I think you are just setting the error to the variable $result and leaving it there, you may need to echo or return or print…

yeah, opps silly mistake :blush: