Python:最终需要一个try-except子句吗?

时间:2018-03-21 08:40:32

标签: python except finally

假设以下代码。

try:
    some_code_1
except: # will it be called twice, if an error occures in finally?
    some_code_2
finally:
    some_code_3

假设some_code_3发生异常。我是否需要some_code_3周围的额外try-except子句(见下文),或者是否会再次调用some_code_2的异常,这原则上会导致无限循环?

这是救星?

try:
    some_code_1
except: # will it be called twice, if an error occures in finally?
    some_code_2
finally:
    try:
        some_code_3
    except:
        pass

3 个答案:

答案 0 :(得分:3)

试一试:

    Intitialize cordova camera on device ready, 
    In index.html add this

    <script>
    var destinationType;
    var pictureSource ;
    document.addEventListener("deviceready", onDeviceReady, false);

    function onDeviceReady() {

        if (cordova.platformId == 'android') {

        }
            pictureSource=navigator.camera.PictureSourceType;
            destinationType=navigator.camera.DestinationType;

        //document.addEventListener("backbutton", onBackKeyDown, false);


    }




   // Now invoke the below function on button click
    function takePicture() {
            var options = {
                    quality: 100,
                    destinationType: Camera.DestinationType.DATA_URL,
                    sourceType: Camera.PictureSourceType.CAMERA,
                    mediaType: Camera.MediaType.CAMERA,
                    encodingType: Camera.EncodingType.PNG,
                    targetWidth: 200,
                    targetHeight: 200,
                    allowEdit : true,
                    saveToPhotoAlbum: true
                };
            navigator.camera.getPicture(onSuccess, onFail,options);

            }
        function onSuccess(imageUri) {
            var image = document.getElementById('img1');
            image.src = "data:image/png;base64," + imageUri;



        }
        function onFail(){

         //your error block here
        }

     </script> 


    please try this, it works fine for me.

所以不,它不会以无限循环结束

答案 1 :(得分:2)

python不会返回执行流程,而是声明语句。

到达finally时,如果在那里抛出错误,则需要另一个句柄

答案 2 :(得分:2)

示例代码中的 finally 不会从some_code_3中捕获异常。

是否需要从some_code_3捕获异常取决于您的设计。