Exception Handling
Ek try block us code ko run karta hai jo ek exception throw kar sakta hai; ek matching catch block agar woh throw ho to use handle karta hai. Yahan ArithmeticException ek unchecked exception hai — compiler aapko ise handle karna require nahi karta, halaanki ise handle karna achhi practice hai.
public class Main {
static int divide(int a, int b) {
return a / b;
}
public static void main(String[] args) {
try {
System.out.println(divide(10, 2));
System.out.println(divide(10, 0));
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}5 Error: / by zero
Checked exceptions: ek real compile error kaisa dikhta hai
Java ke paas ek doosri category hai jiska is site ki doosri languages mein koi equivalent nahi: checked exceptions. Ek method jo ek throw kar sakta hai, jaise yahan IOException, use ya to use catch karna padta hai ya apne khud ke signature mein throws IOException declare karna padta hai — agar woh dono mein se kuch nahi karta, to code bas compile hi nahi hota. Yeh genuinely woh hai jo javac report karta hai — ek real run se capture kiya gaya hai, plausible dikhne ke liye likha nahi gaya:
import java.io.IOException;
public class Main {
static void risky() throws IOException {
throw new IOException("something went wrong");
}
public static void main(String[] args) {
risky();
}
}Main.java:9: error: unreported exception IOException; must be caught or declared to be thrown
risky();
^
1 errorrisky(), throws IOException declare karta hai, jo method ka apna part of the deal hai — lekin main(), risky() ko bina us exception ko catch kiye ya apna khud ka throws declare kiye call karta hai, isliye compiler build karne se mana kar deta hai. Call ke around try/catch add karna, ya main ke khud ke signature mein throws IOException add karna, dono tarike se theek ho jaata.
Aage: generics — ek class ya method likhna jo kai types ke across kaam kare, compiler phir bhi type safety check karte hue.
Practice exercise
Ek method safeDivide(int a, int b) likho jo a / b return kare, lekin ArithmeticException catch kare aur 0 return kare agar b 0 ho. Use (10, 0) ke sath call karo aur result print karo.