فهرس المقرر
تدريب عملي

التدريب العملي 16: Checked و Unchecked في برنامج واحد

FileReader يتطلب معالجة إلزامية، ثم ثلاثة استثناءات وقت التشغيل حسب ما يُدخله المستخدم.

trymyNumbers[10] ! catch (Exception e)

من الدرس 11. الاستثناءات Exceptions · كل التدريبات

١نص المسألة

اكتب برنامجًا يعالج نوعين من الاستثناءات: استثناء متحقق Checked عند فتح ملف غير موجود data.txt، واستثناءات غير متحققة Unchecked عند قراءة رقم فهرس من المستخدم لطباعة درجة من مصفوفة الدرجات، مع finally ورسالة تؤكد استمرار البرنامج.

٢الخوارزمية المقترحة

  1. الجزء الأول: try { new FileReader("data.txt") } catch (FileNotFoundException e) واطبع e.getMessage()، و finally تطبع رسالة.
  2. الجزء الثاني: مصفوفة الدرجات {90, 88.50, 77, 100, 50} وكائن Scanner.
  3. داخل try: اقرأ الفهرس بـ nextInt واطبع الدرجة، ثم السطر 10 / 0.
  4. catch (InputMismatchException) لإدخال غير صحيح، و catch (ArrayIndexOutOfBoundsException) لفهرس خارج الحدود، و catch (Exception) لأي خطأ آخر.
  5. بعد الكتل اطبع: Program continues after the try-catch-finally block.

٣خطوات التطبيق

في NetBeans

  1. أنشئ مشروع Lab16 واكتب الكود.
  2. نفّذ ثلاث مرات: أدخل 1.5 ثم 5 ثم 2، ولاحظ أي catch تعمل في كل مرة.

في OneCompiler

  1. افتح OneCompiler من زر «▶ شغّل المشروع» أسفل الحل، أو من موقع onecompiler.com/java.
  2. في OneCompiler تُكتب كل الكلاسات في ملف واحد Main.java؛ زر التشغيل يجمعها لك تلقائيًّا.
  3. إذا كان البرنامج يقرأ من لوحة المفاتيح، فاكتب المدخلات في خانة STDIN التي تظهر تحت الكود في محرّر OneCompiler، ثم اضغط Run.

٤المخرجات المطلوبة

نفّذ برنامجك، ويجب أن تظهر المخرجات التالية:

نواتج التشغيل الثلاثة في NetBeans على ويندوز

الإدخال: 1.5
Output – Lab16 (run)×
run:
data.txt (The system cannot find the file specified)
This code in the finally block always executes.
Enter an index number.(0 to 4): 1.5
Error! input must be an integer number
Program continues after the try-catch-finally block.
BUILD SUCCESSFUL (total time: 0 seconds)
الإدخال: 5
Output – Lab16 (run)×
run:
data.txt (The system cannot find the file specified)
This code in the finally block always executes.
Enter an index number.(0 to 4): 5
Index 5 out of bounds for length 5
Program continues after the try-catch-finally block.
BUILD SUCCESSFUL (total time: 0 seconds)
الإدخال: 2
Output – Lab16 (run)×
run:
data.txt (The system cannot find the file specified)
This code in the finally block always executes.
Enter an index number.(0 to 4): 2
The mark is: 77.0
/ by zero
Program continues after the try-catch-finally block.
BUILD SUCCESSFUL (total time: 0 seconds)

المدخلات المستخدمة: 2

٥الحل المقترح

حاول بنفسك أولًا، ثم قارن حلّك بالحل المقترح (كود التدريب من مذكرة العملي):

👁 اعرض الحل المقترح
package lab16; import java.io.FileNotFoundException;import java.io.FileReader;import java.util.InputMismatchException;import java.util.Scanner; public class Main {     public static void main(String[] args) {        // checked exception example        try {            FileReader file = new FileReader("data.txt");        }        catch (FileNotFoundException e) {            System.out.println(e.getMessage());        }        finally{            System.out.println("This code in the finally block always executes.");            // Resource cleanup or other essential tasks would go here        }         // unchecked exception examples        double marks[] = {90, 88.50, 77, 100, 50};        Scanner scan = new Scanner(System.in);        try {            System.out.print("Enter an index number.(0 to 4): ");            int idx = scan.nextInt();            System.out.println("The mark is: " + marks[idx]);            // This will cause an ArithmeticException            System.out.println( 10 / 0);        }        catch (InputMismatchException  e) {            System.out.println("Error! input must be an integer number");        }        catch (ArrayIndexOutOfBoundsException e) {            System.out.println(e.getMessage());        }        // any other Exceptions: including ArithmeticException        catch(Exception e){            System.out.println(e.getMessage());        }        System.out.println("Program continues after the try-catch-finally block.");    }}
مخطط المشروع مستخرج من الكود. انقر على أي كلاس لفتح كوده.
Main
Main+ main(args : String[]) : void

أسئلة المناقشة

أسئلة مناقشة على التدريب 16. إجاباتك تُحفظ تلقائيًّا على هذا الجهاز؛ أجب ثم اضغط «صحّح ورقتي».

1السؤال الأول: اختر الإجابة الصحيحة

1) ما فائدة وجود كتل متعددة من catch؟
2) في جافا، إذا تم إدخال قيمة -1 كمؤشر "فهرس" index لأحد عناصر المصفوفة، ما الذي سيحدث؟
snippet
System.out.println( marks[-1] );
3) ما الفرق بين FileNotFoundException و ArrayIndexOutOfBoundsException؟
4) ما الذي يعنيه السطر:
snippet
System.out.println(e.getMessage());
5) أي من العبارات التالية صحيحة بخصوص catch؟
6) ما نوع الاستثناء الذي يمكن أن ينتج عن إدخال المستخدم قيمة غير رقمية وقراءتها بواسطة الدلة nextInt
7) ماذا يحدث إذا أدخل المستخدم رقمًا أكبر من 4؟
snippet
double marks[] = {90, 88.50, 77, 100, 50};        Scanner scan = new Scanner(System.in);        try {            System.out.print("Enter an index number.(0 to 4): ");            int idx = scan.nextInt();            System.out.println("The mark is: " + marks[idx]);        }        catch (InputMismatchException  e) {            System.out.println("Error! input must be an integer number");        }        catch (ArrayIndexOutOfBoundsException e) {            System.out.println(e.getMessage());        }
8) ما فائدة الكتلة catch؟
9) ما الهدف من finally في الكود؟
10) 7. في الكود التالي:
snippet
try {FileReader file = new FileReader("data.txt");}catch (FileNotFoundException e) {System.out.println(e.getMessage());}finally {System.out.println("File handling process finished.");}
إذا لم يوجد الملف، ما الذي سيتم طباعته؟
11) في المثال، ما نوع الاستثناءات التي تم معالجتها اجباريا أثناء الترجمة (compile-time)؟
أجب عن الأسئلة ثم اضغط «صحّح ورقتي».