Java gooi sleutelwoord

❮ Java sleutelwoorde


Voorbeeld

Gooi 'n uitsondering as ouderdom onder 18 is (druk "Toegang geweier"). As ouderdom 18 of ouer is, druk "Toegang verleen":

public class Main {
  static void checkAge(int age) {
    if (age < 18) {
      throw new ArithmeticException("Access denied - You must be at least 18 years old.");
    }
    else {
      System.out.println("Access granted - You are old enough!");
    }
  }

  public static void main(String[] args) {
    checkAge(15); // Set age to 15 (which is below 18...)
  }
}


Definisie en gebruik

Die throwsleutelwoord word gebruik om 'n pasgemaakte fout te skep.

Die throwstelling word saam met 'n uitsonderingstipe gebruik . Daar is baie uitsonderingstipes beskikbaar in Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, ens.

Die uitsonderingstipe word dikwels saam met 'n pasgemaakte metode gebruik , soos in die voorbeeld hierbo.

Verskille tussen throwen throws:

throw throws
Used to throw an exception for a method Used to indicate what exception type may be thrown by a method
Cannot throw multiple exceptions Can declare multiple exceptions
Syntax:
  • throw is followed by an object (new type)
  • used inside the method
Syntax:
  • throws is followed by a class
  • and used with the method signature

Verwante bladsye

Lees meer oor uitsonderings in ons Java Try..Catch Tutoriaal .


❮ Java sleutelwoorde