English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

تعليمات Java الأساسية

تحكم في العملية Java

مجموعات Java Array

Java توجيهية (I)

Java توجيهية (II)

Java توجيهية (III)

معالجة الاستثنائات في Java

قوائم Java List

Java Queue (الطابور)

مجموعات Java Map

مجموعات Java Set

إدخال/إخراج Java (I/O)

قراء/كتابة Java

مواضيع أخرى في Java

الكلمة المفتاحية throw والكلمة المفتاحية throws في Java

في هذا الدرس، سنتعلم باستخدام الأمثلة كيفية معالجة الاستثناءات باستخدام كلمات المفتاح throw و throws.

في Java، يمكن تصنيف الاستثناءات إلى نوعين.

  • الاستثناءات غير المدققة:ليسوا مدققين عند التجميع ولكن عند التشغيل، مثل ArithmeticException،NullPointerException،ArrayIndexOutOfBoundsException،و استثناءات تحت فئة Error وما إلى ذلك.

  • الاستثناءات المدققة:تتم مراقبةهم عند التجميع. على سبيل المثال IOException،InterruptedException وما إلى ذلك.

يرجى الرجوع.استثناءات Javaللتفاصيل الكاملة حول الاستثناءات المدققة وغير المدققة.

عادةً لا نحتاج إلى معالجة الاستثناءات غير المدققة. هذا بسبب أن الاستثناءات غير المدققة تحدث بسبب أخطاء برمجة. ويعتبر تصحيحها بدلاً من معالجتها عادة جيدة.

现在,本教程将重点介绍如何使用throw和throws处理已检查的异常。

Java throws 关键字

我们在方法声明中使用throws关键字来声明其中可能发生的异常的类型。

جملة النص هي:

accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 … {
  // code
}

从上面的语法可以看到,我们可以用throws来声明多个异常。

示例1:Java throws 关键字

import java.io.*;
class Main {
  public static void findFile() throws IOException {
    //可能产生IOException的代码
    File newFile=new File("test.txt");
    FileInputStream stream=new FileInputStream(newFile);
  }
  public static void main(String[] args) {
    try{
      findFile();
    } catch(IOException e){
      System.out.println(e);
    }
  }
}

Output Result

java.io.FileNotFoundException: test.txt (No such file or directory)

当我们运行这个程序时,如果文件test.txt不存在,FileInputStream将抛出一个继承IOException类的FileNotFoundException异常。

如果方法不处理异常,则必须在throws子句中指定该方法中可能发生的异常类型,以便调用堆栈中更高层的方法可以处理它们或使用throws关键字本身指定它们。

findFile()方法指定可以抛出IOException。 main()方法调用此方法并处理抛出的异常。

引发多个异常

这是我们如何使用throws关键字引发多个异常的方法。

import java.io.*;
class Main {
  public static void findFile() throws NullPointerException, IOException, InvalidClassException {
    
    // 可能产生NullPointerException的代码
    … … … 
    // 可能产生IOException的代码
    … … … 
    // 可能产生InvalidClassException的代码 
    … … … 
  }
  public static void main(String[] args) {
    try{
      findFile();
    catch(IOException e1){
      System.out.println(e1.getMessage());
    } catch(InvalidClassException e2){
      System.out.println(e2.getMessage());
    }
  }
}

في هذا، يحدد طريقة findFile() أنها يمكن أن ترفع NullPointerException وIOException وInvalidClassException في جملة throws الخاصة بها.

لاحظ أننا لم نعالج استثناء NullPointerException. هذا لأنه استثناء غير مفتقح. لا يجب على throws تحديد ذلك ومعالجته.

كلمة المفتاح throws مع try...catch...finally

قد تكون هناك عدة طرق تؤدي إلى استثناء. كتابة try...catch لكل طريقة سيكون مملًا، وسيصبح الكود طويلًا ومشوشًا.

عندما تكون قد قمت بالتحقق من الاستثناءات التي لا ترغب في القبض عليها في الوقت الحالي (الاستثناءات التي يجب معالجتها) فإن throws تكون مفيدة أيضًا.

كلمة المفتاح throw في Java

كلمة المفتاح throw用于 إطلاق استثناء بشكل صريح.

عندما يتم إطلاق الاستثناء، ينتقل مسار تنفيذ البرنامج من جسم try إلى جسم catch. نستخدم كلمة المفتاح throw في الدالة.

جملة النص هي:

throw throwableObject;

مثال على Throwable هو نموذج Throwable أو فرع منه.

مثال 2: كلمة المفتاح throw في Java

class Main {
  public static void divideByZero() {
    throw new ArithmeticException("حاولت قسمة 0");
  }
  public static void main(String[] args) {
    divideByZero();
  }
}

Output Result

Exception in thread "main" java.lang.ArithmeticException: حاولت قسمة 0
    at Main.divideByZero(Main.java:3)
    at Main.main(Main.java:7)
حالة الخروج 1

في هذا المثال، نرفع بوضوح ArithmeticException.

ملاحظة: ArithmeticException هو استثناء غير مفتقح. عادة لا يكون من الضروري معالجة الاستثناءات غير المفتقحة.

مثال 3: رمز تحقق من الاستثناء

import java.io.*;
class Main {
  public static void findFile() throws IOException {
    throw new IOException("File not found");
  }
  public static void main(String[] args) {
    try {
      findFile();
      System.out.println("The remaining code in the try block");
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }
}

Output Result

File not found

The findFile() method throws an IOException by passing a message to its constructor.

Note that since it is a checked exception, it must be specified in the throws clause.

The method that calls findFile() needs to handle this exception, or it can specify it using the throws keyword.

We have handled this exception in the main() method. When an exception is thrown, the program execution flow transfers between the try blocks to catch. Therefore, the remaining code in the try block will be skipped, and the statements in the catch block will be executed.