Hướng dẫn php nested try catch

Try-catch blocks in PHP can be nested up to any desired levels and are handled in reverse order of appearance i.e. innermost exceptions are handled first. Nested blocks can be useful in case a block of code causes an exception, which can be handled within that block and program execution can continue in the outer block. They can also be useful in case the handling of an exception causes another exception.

Here is an example of a nested try-catch block:

try{
   try{
      if[file_exists["myfile.json"]]{
         //upload file
      } else {
         throw new Exception[ 'File not found'];  
      }
   }
   catch [Exception $e]{
      throw new Exception[ 'Unable to upload file',0,$e];
   }
   //continue outer try block code
}
catch [Exception $e]{
   echo $e->getMessage[] . "
"; while[$e = $e->getPrevious[]] { echo 'Previous exception: '.$e->getMessage[] . "
"; } }

In this example, a file is uploaded and it is checked whether the file exists or not prior to the upload operation. If it does not exist, an exception is thrown. This code that checks whether the file exists or not is placed within a try-catch block, which is nested within another try-catch block.

In case the file is not found, the inner block throws an 'Unable to upload file' exception, which is caught and handled by the outer block, leading to the following output:

Unable to upload file
Previous exception: File not found

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing PHP errors easier than ever. Try it Today!

Consider:

try{
    class MyException extends Exception{}
    try{
        throw new MyException;
    }
    catch[Exception $e]{
        echo "1:";
        throw $e;
    }
    catch[MyException $e]{
        echo "2:";
        throw $e;
    }
}
catch[Exception $e]{
    echo get_class[$e];
}

I am confused with this try and catch. I am expecting a 2:MyException result because of the second try throw MyException. But the actual result is 1:MyException. What is the explanation?

asked Oct 5, 2013 at 23:55

1

MyException extends Exception, so Exception is more general than MyException, and the first catch block will catch it. If you want to catch MyException you need to reverse the order of the catch blocks:

class MyException extends Exception{}

try {
 try {
   throw new MyException;
 } catch[MyException $e]{
   echo "2:";
   throw $e;
 } catch[Exception $e]{
   echo "1:";
   throw $e;
 }
}catch[Exception $e]{
echo get_class[$e];
}

NessBird

6851 gold badge6 silver badges15 bronze badges

answered Oct 6, 2013 at 0:02

The first catch-block catches everything of the 'Exception' class. Since your MyException extends the Exception-class, the MyException is caught in this first catch-block.

answered Oct 5, 2013 at 23:59

It would be better if you check the classname and handle it accordingly.

class MyException extends Exception {}

try {
    throw new MyException;
}
catch [Exception $ex]{
    switch [get_class [$ex]] {

       case "MyException" :
           // Do whatever you want to do for MyException
           break;

       default:
           // Do whatever you want to do for Exception
           break;
   }
   throw $ex;
}

answered Aug 27, 2014 at 1:35

Rx SevenRx Seven

5293 silver badges11 bronze badges

Hướng dẫn mongodb connection

Nội dung bài viếtVideo học lập trình mỗi ngàyConnect server MongoDB từ xa hay từ một server khác đó là một mô hình bình thường hiện nay. Bài viết này sẽ ...

Can you have 2 variables in a for loop python?

I think you are looking for nested loops. Example [based on your edit]:t1=[1,2,Hello,[1,2],999,1.23] t2=[1,Hello,[1,2],999] t3=[] for it1, e1 in enumerate[t1]: for it2, e2 in ...

Hướng dẫn nodejs docker timezone

Hướng dẫn dùng asia time trong PHPĐôi lúc các bạn xem các hướng dẫn về hàm lấy thời gian :date[format,timestamp].Nội dung chínhTIMEZONE LÀ GÌ?CÁCH CHỈNH TIMEZONE ...

Hướng dẫn lookup array mongodb

Yêu cầu thg 7 31, 2018 7:31 SA• 4215 0 0Chào mọi người. Mình có 1 app đang làm sử dụng mongodb. Do mới tiếp xúc nên có vấn đề mình gặp phải cần mọi người ...

Hướng dẫn using json in nodejs

Nội dung bài viếtVideo học lập trình mỗi ngàyJSON NodeJS [JavaScript Object Notation] được sử dụng rộng rãi trong việc chia sẻ dữ liệu với nhiều ngôn ngữ khác ...

Hướng dẫn nested try-catch php

Try-catch blocks in PHP can be nested up to any desired levels and are handled in reverse order of appearance i.e. innermost exceptions are handled first. Nested blocks can be useful in case a block ...

How do i enable php error logging?

When developing PHP applications, error logs are under-used because of their apparent complexity. PHP error logs are helpful, especially when configured and used properly.While there are advanced ...

Hướng dẫn nodejs mongoose

Mongoose là một thư viện mô hình hóa đối tượng [Object Data Model - ODM] cho MongoDB và Node.js. Nó quản lý mối quan hệ giữa dữ liệu, cung cấp sự xác nhận giản ...

Hướng dẫn dùng f try python

Hàm try[] được sử dụng trong việc xử lý lỗi và ngoại lệ trong PythonNội dung chínhException là gì?Mệnh đề except mà không xác định Exception trong PythonMệnh ...

Hướng dẫn dùng exception handling python

Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi người. Là ...

Get data from mongodb node js

In MongoDB we use the find and findOne methods to find data in a collection.Just like the SELECT statement is used to find data in a table in a MySQL database.Find OneTo select data from a collection ...

Hướng dẫn raise except in python

Until now error messages haven’t been more than mentioned, but if you have tried out the examples you have probably seen some. There are [at least] two distinguishable kinds of errors: syntax ...

Hướng dẫn nodejs express form-data

Khi một web client tải một tệp lên máy chủ, nó thường được gửi qua một biểu mẫu và được mã hóa dưới dạng dữ liệu multipart/form-data. Multer là một ...

Hướng dẫn env file nodejs

Đã đăng vào thg 11 22, 2019 4:15 SA 2 phút đọc 1. Mở đầu:Nếu bạn quan tâm đến việc làm cho ứng dụng của bạn chạy trên bất kỳ máy tính hoặc cloud ...

Hướng dẫn import excel reactjs

Chúng ta thường xuất dữ liệu từ bảng sang bảng excel trong các ứng dụng web. Có hai cách để thực hiện chức năng export trong React: một là sử dụng bất kỳ ...

Nodejs add element to json object

You can also add new json objects into your json, using the extend function,var newJson = $.extend[{}, {my:json}, {other:json}]; // result -> {my: json, other: json} A very good option for ...

Hướng dẫn nodejs getter setter

Bài viết này tham khảo từ bài viết Ultimate Guide to Getters and Setters in JavaScript getter và setter là các hàm hoặc phương thức được dùng để lấy ra hoặc thiết ...

What does apply [] do in javascript?

Method ReuseWith the apply[] method, you can write a method that can be used on different objects.The JavaScript apply[] MethodThe apply[] method is similar to the call[] method [previous chapter].In ...

Hướng dẫn dùng nested loops python

Thứ năm, 12/01/2017 | 00:00 GMT+7 Nội dung chính Đối với các vòng lặp Đối với các vòng lặp sử dụng dải ô [] Đối với vòng lặp sử dụng kiểu dữ liệu ...

Hướng dẫn dùng python raise python

python Return trong Python Function trong Python Hàm trong PythonNội dung chínhBài Viết Liên QuanToplist mớiBài mới nhấtChủ Đề8.1. Syntax Errors¶8.2. Exceptions¶8.3. Handling ...

Học nodejs từ cơ bản đến nâng cao

Học Node.js cơ bản và nâng caoNode.js là một Framework mạnh mẽ dựa trên nền tảng Google Chrome Javascript V8 Engine. Node.js được dùng để phát triển các ứng dụng ...

Hướng dẫn khóa học nodejs online

Giới thiệu khóa họcBạn có biết:Node.js là 1 nền tảng phát triển ứng dụng phía server. Nó sử dụng ngôn ngữ lập trình JavaScript. Mỗi kết nối đến sẽ sinh ...

Hướng dẫn php get error trace

[PHP 7, PHP 8]Error::getTrace — Gets the stack traceDescriptionfinal public Error::getTrace[]: arrayParametersThis function has no parameters.Return Values Returns the stack trace as an array. ...

Hướng dẫn list comprehension python problems

When to Use a List Comprehension in Pythonby James Timmins basics pythonMark as Completed Tweet Share EmailTable of ContentsNội dung chínhWhen to Use a List Comprehension in PythonHow to Create ...

Hướng dẫn nodejs live streaming

Streams trong NodeJS là gì ?Streamstrong NodeJS là một collections của dữ liệu giống như strings hay arrays, sự khác nhau duy nhất đó là các streams không tồn tại ...

What is exception handling in php with example?

Exception handling is a powerful mechanism of PHP, which is used to handle runtime errors [runtime errors are called exceptions]. So that the normal flow of the application can be maintained.The main ...

What is an exception in php?

Exceptions are used to change the normal flow of a script if a specified error occurs.What is an ExceptionWith PHP 5 came a new object oriented way of dealing with errors.Exception handling is used ...

Hướng dẫn insert mongodb nodejs

Phần trước, mình đã hướng dẫn mọi người tạo mới một collection trong MongoDB rồi. Thì sau khi đã tạo được collection rồi bài này chúng ta sẽ cùng nhau tìm ...

Hướng dẫn curl timeout php

Bạn sẽ cần phải đảm bảo về thời gian chờ giữa bạn và tệp. Trong trường hợp này PHP và Curl.Để yêu cầu Curl không bao giờ hết thời gian chờ khi chuyển ...

How do you combine lists within a list python?

For one-level flatten, if you care about speed, this is faster than any of the previous answers under all conditions I tried. [That is, if you need the result as a list. If you only need to iterate ...

Hướng dẫn gprc nodejs

Giới thiệugRPC là một framework RPC [viết tắt của Remote Procedure Call] được phát triển bởi Google, nhằm tối ưu hoá và tăng tốc việc giao tiếp giữa các service ...

Kết hợp nodejs và reactjs

Trong bài viết này, tôi muốn cho bạn thấy cách build front và back-end của một website sử dụng NodeJS làm back-end. Chúng ta sẽ dùng node để tạo các endpoint, và ...

Hướng dẫn nodejs html

Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi người. Là ...

Hướng dẫn nodejs simple api

Xin chào mọi người, hôm nay mình muốn demo cho những bạn chưa từng làm việc với ngôn ngữ Nodejs hoặc đơn giản là muốn tạo một RESTful API với NodeJS REST là ...

Hướng dẫn php try catch finally

Trong bài này, chúng ta sẽ tìm hiểu về ngoại lệ [exception] trong PHP. Để học tốt bài này, các bạn cần đọc lại bài Cài đặt môi trường lập trình Web PHP ...

What is throw exception php?

Table of ContentsExtending Exceptions PHP has an exception model similar to that of other programming languages. An exception can be thrown, and caught [catched] within PHP. Code may be surrounded ...

Hướng dẫn dùng thisbis JavaScript

- Để sử dụng JavaScript trong trang web, chúng ta có hai cách cơ bản như sau:Nội dung chính2] Viết mã lệnh trực tiếp vào trang web2] Viết mã lệnh vào tập tin ...

Chủ Đề