الرجوع الي الدرس

Finally أم الكود فقط؟

الأهمية: 5

قارن بين جزئي الكود.

  1. The first one uses finally to execute the code after try...catch:

    try {
      work work
    } catch (err) {
      handle errors
    } finally {
      تنظيف مكان العمل
    }
  2. The second fragment puts the cleaning right after try...catch:

    try {
      work work
    } catch (err) {
      handle errors
    }
    
    تنظيف مكان العمل

نحن بالتأكيد بحاجة إلى التنظيف بعد العمل ، لا يهم إذا كان هناك خطأ أم لا.

هل هناك ميزة في استخدام finally أم أن جزئي الكود متساويان؟ إذا كان هناك مثل هذه الميزة ، فقم بإعطاء مثال عندما يكزن مهم.

يصبح الفرق واضحًا عندما ننظر إلى الكود داخل دالة.

The behavior is different if there’s a “jump out” of try...catch.

For instance, when there’s a return inside try...catch. The finally clause works in case of any exit from try...catch, even via the return statement: right after try...catch is done, but before the calling code gets the control.

function f() {
  try {
    alert('إبدء');
    return "النتيجة";
  } catch (err) {
    /// ...
  } finally {
    alert('نظف!');
  }
}

f(); // نظف!

…أو عندما يكون هناك throw, مثلما هو الحال هنا:

function f() {
  try {
    alert('إبدء');
    throw new Error("an error");
  } catch (err) {
    // ...
    if("can't handle the error") {
      throw err;
    }

  } finally {
    alert('نظف!')
  }
}

f(); // نظف!

يضمن finally التنظيف. إذا وضعنا الكود في نهاية f, فلن يتم تشغيلها في هذه المواقف.