مرکزی مواد پر جائیں
eLearner.app
ماڈیول 5 · سبق 1 از 2کورس میں 9/14~12 min
ماڈیول اسباق (1/2)

کیچ بلاکس کی کوشش کریں۔

In Java, runtime errors are handled using Exceptions. Exception handling allows us to intercept anomalous conditions and prevent the program from crashing.

The try-catch structure

To handle a potential exception, we enclose the risky code in a try block. If an error occurs inside the try block, the JVM stops executing it and searches for a matching catch block to handle the exception.

Code
try {
    int result = 10 / 0; // Generates ArithmeticException
    System.out.println("This will not be printed");
} catch (ArithmeticException e) {
    System.out.println("Arithmetic error occurred: " + e.getMessage());
}

The finally block

The finally block is optional and is always executed, regardless of whether an exception was thrown. It is ideal for releasing resources or performing cleanup operations.

Code
try {
    System.out.println("Executing logic");
} catch (Exception e) {
    System.out.println("Error");
} finally {
    System.out.println("This block is always executed");
}

Throwing Exceptions: throw

We can intentionally throw an exception using the throw keyword followed by a new instance of an exception class.

Code
public static void checkScore(int score) {
    if (score < 0 || score > 100) {
        throw new IllegalArgumentException("Score must be between 0 and 100");
    }
}

Try it yourself

ورزش#java.m5.l1.e1
کوششیں: 0لوڈ ہو رہا ہے…

Complete the code by inserting a try-catch block to handle a potential ArithmeticException resulting from the division a / b. In case of an error, print 'Error: division by zero'.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

Insert the division operation inside a `try` block and catch `ArithmeticException`, printing the required message.

3 کوششوں کے بعد حل دستیاب ہے۔

ورزش#java.m5.l1.e2
کوششیں: 0لوڈ ہو رہا ہے…

Complete the code to implement a try-catch-finally block. In the try block, try to convert the string str to an integer using Integer.parseInt. In the catch block, intercept NumberFormatException and print 'Invalid number'. In the finally block, print 'Finally'.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

Write the `try { ... } catch (NumberFormatException e) { ... } finally { ... }` block structure.

3 کوششوں کے بعد حل دستیاب ہے۔

ورزش#java.m5.l1.e3
کوششیں: 0لوڈ ہو رہا ہے…

Complete the checkAge method by throwing an IllegalArgumentException with the message 'Underage' if the provided age is less than 18.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

Use `if (age < 18)` and the `throw new` keywords to instantiate and throw the exception.

3 کوششوں کے بعد حل دستیاب ہے۔