Hướng dẫn nested try catch python

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

I have following code, in which i have to handle exception for 2 statements,

2nd line and 4th line

if[re.search["USN:.*MediaRenderer", datagram, flags=re.IGNORECASE]]:
    deviceXML = re.search["LOCATION:[.*.xml]", datagram, flags=re.IGNORECASE].group[1]   # this line            
    root = ElementTree.fromstring[urllib2.urlopen[XMLLocation].read[]]                
    friendlyName = root.find['.//{}friendlyName'.format[Server.namespace]].text   # this line
    if not friendlyName in deviceList.keys[]:
       deviceList[friendlyName] = host
    self.model.setStringList[deviceList.keys[]]

How can i use nested try/catch here

I tried following way:

if[re.search["USN:.*MediaRenderer", datagram, flags=re.IGNORECASE]]:
        try:
            deviceXML = re.search["LOCATION:[.*.xml]", datagram, flags=re.IGNORECASE].group[1]            
            root = ElementTree.fromstring[urllib2.urlopen[XMLLocation].read[]]                
            try:
                friendlyName = root.find['.//{}friendlyName'.format[Server.namespace]].text
                print "\n fname = ", friendlyName
                if not friendlyName in deviceList.keys[]:
                    deviceList[friendlyName] = host
                self.model.setStringList[deviceList.keys[]]                
        except:
            pass

This is giving me indentation error for except line

Chủ Đề