Hirenix kaise padhata hai
Ek chapter. 90 minute.
Interview ke liye taiyaar.
Har concept ek real-world problem se — jaisa production code mein aata hai, waisa. Ratna nahi padta, samajh aa jaata hai. Har question ka model answer diya hai: interviewer ko exactly kya bolna hai, aur kyun. Phir usi chapter ka AI mock interview.
- 📖Concept, 5 min meinJargon nahi — seedhi baat
- 🛠️Real-world problemJaisa production code mein aata hai
- 💬Model answerInterview mein kya bolna hai
- 🧠FlashcardsRevision 10 min mein
- 🤖AI mock interviewFollow-up bhi poochta hai
- 📊Weak topicsKahan phans rahe ho, pata chale

Farq content ka nahi, filter ka hai — sirf wahi jo production mein actually use hota hai aur interview mein actually poocha jaata hai. Kitaabi topics jo industry mein kahin nahi chalte, wo yahan nahi milenge.
What you’ll learn
- ●Exception kya hai aur Throwable ka naksha
- ●Checked vs unchecked exceptions
- try, catch, finallyFree account
- throw vs throws, aur propagationFree account
- Multi-catch aur catch ka orderFree account
- try-with-resources aur suppressed exceptionsFree account
- Apni exception banana aur chainingFree account
- Stack trace padhna aur naye NPE messagesFree account
- Exception ke antipatterns aur best practicesFree account
- Overriding aur throws ka ruleFree account
- File aur Path: java.io vs java.nio.fileFree account
- Text file padhna aur likhnaFree account
- Streams, buffering aur character encodingFree account
- Serialization ki buniyaadFree account
- RecapFree account
- ●Project: CSV Report Loader
- Project: Log File AnalyzerFree account
- Project: Notes File ManagerFree account
Exception kya hai aur Throwable ka naksha
Ek railway reservation counter sochiye. Ek clerk, ek line, aur tay kadam: form lo, train check karo, ticket print karo, de do.
Ek hi subah teen cheezein bigadti hain.
Ek passenger aisi train maangta hai jo hai hi nahi. Clerk rukta hai, kehta hai "aisi koi train nahi", aur agle aadmi ko bulata hai. Kaam chalta raha.
Printer ka paper khatam ho jaata hai. Clerk rukta hai, paper daalta hai, dobara print karta hai. Thoda slow, par counter khula hai.
Phir station ki bijli chali jaati hai aur backup bhi mara hua hai. Ab clerk kuch bhi nahi kar sakta. Paper daalna kaam nahi aayega. Dhyan se kaam karna bhi kaam nahi aayega. Counter band.
Pehli do wo halat hain jinke liye clerk taiyaar hai. Teesri us zameen ka fail hona hai jis par wo khada hai. Java theek yahi lakeer kheenchta hai, aur is chapter ka baaki har topic isi ka nateeja hai.
Production mein "train nahi hai" aur "paper khatam" wale case exceptions hain — kharab date string, gayab file, ya null jahan aapne object socha tha. Aapka code inhe catch karke kuch samajhdaari wala kaam kar sakta hai: dobara poochho, default use karo, kharab row log karke agli row pe badh jao. Bijli ka jaana Error hai — JVM ka apna heap khatam ho gaya ya uska stack bhar gaya. Ab koi samajhdaar recovery bachi hi nahi, kyunki jo machinery aapka recovery code chalati, wahi toot chuki hai.
Mechanism ek hi line ka hai. Jab kisi method ko dikkat aati hai to wo ek object throw karta hai. Uske baad JVM call stack par wapas upar chalta hai, ek-ek frame, aur wo sabse nazdeeki catch dhoondhta hai jiska type us object se match kare. Jaise hi mil jaata hai, control wahan chala jaata hai aur program aage badh jaata hai. Agar kahin nahi milta, to JVM stack trace print karke thread ko maar deta hai — yahi wo "Exception in thread main..." wala crash hai jo aap dekh chuke hain.
🌍 Real-world example: ek payments service raat mein 5,000 refunds ki CSV padhti hai. Row 4,182 mein amount
1200ki jagah1,200likha hai. Wo rowNumberFormatExceptionthrow karti hai. Handle kiya, to job ek row chhod deti hai aur 4,999 refunds nikal jaate hain; handle nahi kiya, to poora thread mar jaata hai aur baaki har customer subah tak intezaar karta hai. Ek hi defect, do bilkul alag Monday.
💡 Exception = aisi ghatna jo runtime par program ka normal flow tod deti hai, aur jo ek object ki shakl mein hoti hai. 💡
Throwable= poore khandaan ki root class,java.langmein. Sirf yahi type Javathrowke baad yacatchke andar likhne deta hai.throw "oops";compile hi nahi hota — javac kehta haiincompatible types: String cannot be converted to Throwable. 💡Error=Throwableki seedhi subclass, JVM ya environment ke fail hone ke liye. Inhe catch karna aapka kaam nahi hai. 💡Exception=Throwableki doosri seedhi subclass, un haalaat ke liye jinhe application se handle karne ki umeed ki ja sakti hai. 💡RuntimeException=Exceptionki wo subclass jiski aulaad par compiler pehra nahi deta. Yahi unchecked wale hain —NullPointerException,ArithmeticException,IllegalArgumentException. 💡 Stack unwinding = matchingcatchdhoondhte hue JVM ka ek-ek call frame girate jaana.
Naksha — ise bana lijiye, baaki sab isi se nikal aayega
Object
|
Throwable <- the ONLY type you can throw or catch
/ \
Error Exception "the app can reasonably handle this"
| / \
VirtualMachineError / RuntimeException
/ \ / / | \
StackOverflowError OutOfMemoryError NullPointer Arithmetic IllegalArgument
| Exception Exception Exception
IOException, SQLException,
ClassNotFoundException, ... UNCHECKED
CHECKED (compiler forces you) (compiler stays quiet)
Is tasveer mein chaar baatein zor se bolne layak hain, kyunki interviewer inhi par ungli rakhta hai.
Throwable hi darwaza hai. Is ped ke bahar ki koi cheez na throw ho sakti hai na catch. Isiliye ye khandaan ka ped matter karta hai: catch type se match karta hai, to class kahan baithi hai wahi tay karta hai ki use kaun pakdega. catch (Exception e) Exception ke neeche ki har shaakh pakadta hai — aur Error ke neeche ka kuch bhi nahi.
Error aur Exception bhai-bhai hain, baap-beta nahi. Error ek Exception nahi hai. Neeche wala demo chala kar dekhiye, false aayega — aur ye bhi pata chalega ki us check ka "seedha" version compile hi nahi hota.
RuntimeException Exception ke neeche hai. Yaani har RuntimeException ek Exception hai, aur isi wajah se catch (Exception e) chupchaap NullPointerException bhi nigal jaata hai. Checked/unchecked ka batwara ped mein nahi hai, wo ek rule hai jo compiler is ped ki ek shaakh par lagata hai. Topic 2 poora usi rule ka hai.
Stack trace sirf Throwable ke paas hai. getMessage(), getCause() aur printStackTrace() isi se aate hain, aur isiliye aap apna error type shoonya se nahi bana sakte — aapko isi ped ki kisi class ko extend karna padta hai.
Error vs Exception — recover karne layak kaun hai
Exception |
Error |
|
|---|---|---|
| Wajah | aapka code ya bahar ki duniya | khud JVM ya environment |
| Udaharan | IOException, NumberFormatException, NullPointerException |
StackOverflowError, OutOfMemoryError, NoClassDefFoundError |
| Recover? | aksar haan — retry, default, skip | koi matlab ki recovery nahi |
| Compiler ka rol? | haan, checked shaakh par | kabhi nahi |
| Aapka kadam | wahan catch karo jahan kuch kar sakein, warna upar jaane do | process ko marne do, phir wajah theek karo |
Asli test ye nahi hai ki "sunne mein kitna bura lag raha hai". Asli test ye hai: kya mere program ke paas koi aisa kadam hai jo is haal ko behtar kar de? Gayab config file ke paas hai — default pe chale jao, ya aise message ke saath fail ho jao jis par insaan kaam kar sake. Bhare hue heap ke paas nahi hai; wahan log message banane ki koshish bhi fail ho sakti hai.
ClassNotFoundException vs NoClassDefFoundError
Ye jodi dono badi interview lists par hai, aur ye Error / Exception wale batware ka sabse saaf asli udaharan hai — isiliye ye yahan hai, kisi trivia list mein nahi.
ClassNotFoundException ek checked Exception hai. Ye tab aati hai jab aap khud runtime par naam se class maangte hain — Class.forName("com.mysql.cj.jdbc.Driver"), ya koi reflective lookup, ya class loader — aur loader use dhoondh nahi paata. Aapke code ne poocha tha, isliye aapka code jawab bhi de sakta hai: catch kijiye, "MySQL driver JAR classpath mein nahi hai" print kijiye, saaf message ke saath exit ho jaaiye. Neeche wala demo yahi karta hai aur program aage chalta rehta hai.
NoClassDefFoundError ek Error hai. Iska matlab hai ki class compile ke waqt maujood thi par ab load nahi ho pa rahi. JVM us par bharosa kar chuka tha, isliye ye ek toota hua environment hai, koi fail hui request nahi. Sabse aam asli wajah gayab jar bhi nahi hai — wajah aksar wo class hoti hai jiska static initializer pehli baar chhoote hi phat gaya. Pehla access ExceptionInInitializerError deta hai; uske baad har access NoClassDefFoundError deta hai, kyunki class ab hamesha ke liye na-kaabil-e-istemaal mark ho chuki hai:
access 1 -> java.lang.ExceptionInInitializerError
access 2 -> java.lang.NoClassDefFoundError
Ye asli output hai us class ka jiska static final int VALUE = Integer.parseInt("nahi-number"); fail hua tha. Interview ke liye ek line ka jawab: ClassNotFoundException = aapne naam se maanga aur wo mili nahi. NoClassDefFoundError = compile ke waqt thi, par ab JVM use load nahi kar pa raha. Ek fail hui request hai; doosra toota hua environment.
StackOverflowError vs OutOfMemoryError
Ch1 memory model padha chuka hai, isliye yahan sirf ishaara: stack call frames aur locals rakhta hai, heap objects rakhta hai. Do jagah, do errors — aur dono VirtualMachineError hain, aur yahi superclass ka naam bata deta hai ki khud JVM ne haath khade kar diye.
StackOverflowError— stack khatam ho gaya. Lagbhag hamesha wo recursion jiska base case nahi hai, ya jis tak pahuncha hi nahi jaata. Recursion theek kijiye, ya use loop mein likh dijiye.OutOfMemoryError— heap khatam ho gaya. Ya to bahut saare zinda objects, ya wo objects jo kabhi chhode hi nahi jaate.-Xmx32mke saath chalaye gaye ek run par is machine ne messageJava heap spaceprint kiya. Leak ya batch size theek kijiye; bada-Xmxsirf crash ko aage khiska deta hai.
Jo galat jawab nahi dena hai: "dono ka matlab hai memory zyada lag gayi, to memory badha do." StackOverflowError lagbhag hamesha ek logic bug hai, aur koi bhi heap setting use chhoota tak nahi.
Error catch ho sakta hai — aur phir bhi karna nahi chahiye
Mashhoor line hai ki "Error catch nahi ho sakta". Ye galat hai, aur jo interviewer ye jaanta hai wo isi par pakdega. Error Throwable ko extend karta hai, isliye catch (StackOverflowError e) compile bhi hota hai aur chalta bhi hai — neeche wale demo ki line H ne ek pakda, aur uske baad program ne ek line aur print ki.
To phir kyun nahi? Kyunki catch karne se kuch wapas theek nahi hota. OutOfMemoryError ke baad heap ab bhi bhara hua hai aur aapke handler ki apni allocation dobara throw kar sakti hai. StackOverflowError ke baad aap us stack par chal rahe hain jise aap abhi na-kaabil-e-bharosa saabit kar chuke hain. Aapne ek zor-daar, samajh mein aane wale crash ko aise program mein badal diya hai jo anjaan haalat mein ghisatta rehta hai — aur jo log line aap chahte the wo shayad kabhi likhi hi na jaaye. Interview ka jawab: haan, technically ho sakta hai, kyunki Error, Throwable ko extend karta hai — par karna nahi chahiye, kyunki recover karne ko kuch bacha hi nahi. Sirf ek jaayaz istemaal hai: top-level handler jo log kare aur phir exit kar de. Isi wajah se catch (Throwable t) bhi buri aadat hai: wo galti se Error bhi pakad leta hai.
Compiler ki ek baat saath rakhiye: new OutOfMemoryError() instanceof Exception ka jawab false nahi hai — wo khud ek compile error hai, incompatible types. javac saabit kar sakta hai ki ye do types kabhi jud hi nahi sakte, isliye wo sawaal ka jawab dene ke bajaye sawaal hi mana kar deta hai. false tabhi milta hai jab aap Object mein widen karein, aur demo yahi karta hai.
Standard definition (interview me bolo): An exception in Java is an event that disrupts the normal flow of a program at runtime, represented by an object inheriting from java.lang.Throwable; Throwable has two direct subclasses, Error for serious problems an application should not try to recover from, and Exception for conditions a well-written application can catch and handle, with RuntimeException being the unchecked branch of Exception that the compiler does not enforce.
Kab use karein: exception ko us level par catch kijiye jahan aap sach mein uske baare mein kuch kar sakein — rows padhne wala loop kharab-row wali exception pakde taaki baaki 4,999 rows process ho jaayein; controller parse failure pakde aur user ko "invalid date" laut de. Ye ek asli faisla hai, formality nahi.
Kab NAHI use karein: aise level par catch mat kijiye jahan aap sirf dobara log karke rethrow kar sakte hain — use upar jaane dijiye, wahan tak jahan koi faisla ho sake. Aur Error, Throwable, ya aadat ke taur par poore method ke aas-paas khaali Exception kabhi mat pakdiye: yahi wo failures chhupate hain jinhe dekhna sabse zyada zaroori hai, JVM ke apne failures samet. Trade-off: har catch program ko aage chalne ka mauka deta hai aur badle mein aapse ye signal cheen leta hai ki kuch galat hai. Agar aap bata na sakein ki catch block print ke alawa karega kya, to imaandaar chunav yahi hai ki exception ko upar jaane diya jaaye.
public class T1 {
// aisi recursion jo kabhi rukti nahi - stack bhar degi
static void deep(int n) { deep(n + 1); }
// kisi bhi Throwable ka poora parent chain print karta hai
static String chain(Throwable t) {
StringBuilder sb = new StringBuilder();
for (Class<?> c = t.getClass(); c != null; c = c.getSuperclass()) {
if (sb.length() > 0) sb.append(" -> ");
sb.append(c.getSimpleName());
}
return sb.toString();
}
public static void main(String[] args) {
// 1. mechanism: object throw hota hai, type se catch hota hai, program chalta rehta hai
try {
int[] marks = new int[3];
marks[5] = 90;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("A caught : " + e);
}
// 2. naksha sach me maujood hai - classes se khud pooch lijiye
System.out.println("B chain : " + chain(new ArithmeticException("x")));
System.out.println("C chain : " + chain(new java.io.IOException("x")));
System.out.println("D chain : " + chain(new StackOverflowError()));
// 3. Error, Exception NAHI hai. Pehle Object me widen karna padta hai, warna
// javac instanceof ko hi mana kar deta hai - "incompatible types"
Object oome = new OutOfMemoryError("demo");
System.out.println("E OutOfMemoryError instanceof Exception = " + (oome instanceof Exception));
System.out.println("F OutOfMemoryError instanceof Throwable = " + (oome instanceof Throwable));
// 4. ClassNotFoundException - checked Exception, jab AAP naam se class maangte hain
try {
Class.forName("com.hirenix.KoiAisiClassNahiHai");
} catch (ClassNotFoundException e) {
System.out.println("G " + e);
}
// 5. Error catch ho SAKTA hai - aur yahi wo cheez hai jo aapko karni nahi chahiye
try {
deep(1);
} catch (StackOverflowError e) {
System.out.println("H an Error WAS caught: " + e.getClass().getName());
}
System.out.println("I program is still running");
}
}Checked vs unchecked exceptions
Subah ghar se nikalne ka sochiye. Do bilkul alag tarah ki museebat aa sakti hai, aur building dono ko bilkul alag tarah treat karti hai.
Pehli hai aapki apni galti - chaabi mez pe chhod di, ya shishe ke darwaze se takra gaye. Iske liye koi rule nahi ban sakta. Na koi form, na gate pe koi checklist. Bas aadat sudharni padti hai.
Doosri hai baarish. Baarish aapki galti nahi hai. Ye bahar ki duniya ka ek sach hai, jo kisi bhi din, kisi ke saath bhi ho sakta hai, chahe aap kitne hi savdhaan hon. Isliye building ka ek niyam hai, aur gate pe khada security guard use lagu karta hai: aap bahar tab hi ja sakte hain jab ya to aapke haath mein chhata ho, ya aapne ek parcha likh ke diya ho ki "main bina chhate ke ja raha hoon, aur jo mera intezaar kar raha hai use pata hai ki main bheega hua pahunch sakta hoon." Do mein se ek. Agar dono mein se kuch nahi, to guard gate kholta hi nahi.
Aur dhyaan dijiye guard kya nahi karta - chaabi bhool jaane pe wo aapko kabhi nahi rokta.
In production wahi guard hai javac, Java ka compiler. Baarish hai checked exception: aapke program ke bahar ki koi cheez jo fail ho sakti hai chahe aapka code kitna hi accha ho - file gayab, network band, database down. Bhooli hui chaabi hai unchecked exception: aapke apne logic ka bug - array ki hadd ke bahar ka index, ek null jiski ummeed nahi thi, zero se bhaag.
🌍 Real-world example: ek payments service har raat bank ki upload ki hui settlement file padhti hai. Agar bank ka upload job fail ho gaya, to file hai hi nahi. Ye payments service ka bug nahi hai - code perfect hai, duniya nahi. Java developer ko majboor karta hai ki wo saaf-saaf likhe ki us haalat mein kya hoga. Lekin agar wahi service row 200 pe
ArrayIndexOutOfBoundsExceptionde kar gir jaaye, to koi rule kaam nahi aata: wo toota hua loop hai, use fix chahiye, kaagzi karwai nahi.
💡 Checked exception = wo exception jiski compiler jaanch karta hai. Agar koi method use throw kar sakta hai, to har caller ko ya to use catch karna hoga ya declare - warna code compile hi nahi hoga. 💡 Unchecked exception = jo kuch bhi
RuntimeExceptionke neeche hai (aur jo kuchErrorke neeche hai). Compiler iske baare mein kuch nahi kehta; use handle karna poori tarah aapki marzi hai. 💡throws= method ke signature mein likha jaane wala clause jo kehta hai "ye method ye exception aapko wapas de sakta hai - aap sambhaliye". Ye khud kuch handle nahi karta; problem upar bhej deta hai. 💡 Compile time = jabjavacaapka source padh raha hota hai. Runtime = jab JVM program chala raha hota hai. Do alag lamhe, aur ye poora topic isi fark pe khada hai.
Wo jawab jo is sawaal ko sach mein jeet-ta hai
Mashhoor jawab hai "checked compile time pe hoti hai, unchecked runtime pe hoti hai." Ye galat hai, aur accha interviewer bilkul yahi jumla sunne ke liye baitha hota hai.
Compile time pe kuch bhi throw nahi hota. Compiler na aapki file kholta hai, na network milata hai, na ek bhi loop chalata hai. FileNotFoundException aur NullPointerException - dono aise object hain jo program chalte waqt, asli machine pe, asli data ke saath bante aur throw hote hain.
Asli fark hai ek contract jo compiler aap pe thopta hai, .class file banane se pehle:
| checked | unchecked | |
|---|---|---|
| Throw kab hoti hai | runtime | runtime |
javac kuch maangta hai? |
haan - catch karo ya declare karo | nahi - kuch bhi nahi |
| Tree mein kahan baithi hai | Exception ke neeche, RuntimeException se bahar |
RuntimeException ya Error ke neeche |
| Aam taur pe matlab kya | bahar ki duniya fail hui | aapke code mein bug hai |
| Udaharan | IOException, SQLException, InterruptedException |
NullPointerException, ArrayIndexOutOfBoundsException |
Ek line mein boliye: dono runtime ki cheez hain; fark sirf itna hai ki javac aapse source mein kya likhwaata hai.
Naksha - aur wo ek rule jo sab tay karta hai
Throwable
|
+-- Error ................................. UNCHECKED (OutOfMemoryError, StackOverflowError)
|
+-- Exception ............................. CHECKED
|
+-- IOException ..................... checked (FileNotFoundException sits inside this)
+-- SQLException .................... checked
+-- ClassNotFoundException .......... checked
|
+-- RuntimeException ................ UNCHECKED
+-- NullPointerException
+-- ArrayIndexOutOfBoundsException
+-- NumberFormatException
+-- ArithmeticException
+-- ClassCastException
Koi keyword ya annotation nahi hai jo kisi exception ko checked banata ho. Ye sirf isse tay hota hai ki class us tree mein kahan baithi hai. RuntimeException ke neeche sab unchecked. Error ke neeche sab unchecked. Exception ke neeche baaki sab checked. Bas itna hi rule hai, aur isi wajah se NumberFormatException - jo sunne mein bilkul checked lagti hai - unchecked hai: uska parent chain hai IllegalArgumentException -> RuntimeException.
Unchecked exceptions - jinke naam ginwane ko kaha jaayega
| Exception | Kab aati hai |
|---|---|
NullPointerException |
null reference pe method call karne pe |
ArrayIndexOutOfBoundsException |
length 3 wale array pe arr[5] |
NumberFormatException |
Integer.parseInt("abc") |
ArithmeticException |
integer mein 1 / 0 |
ClassCastException |
String ko Integer mein cast karne pe |
IllegalArgumentException / IllegalStateException |
method ko galat input mila, ya galat waqt pe bulaya gaya |
ConcurrentModificationException |
for-each loop chalte waqt list se remove karne pe |
Dekhiye in sab mein common kya hai: har ek code badal kar theek ho sakti hai. Aap ArrayIndexOutOfBoundsException ko "handle" nahi karte - aap loop ki hadd theek karte hain. Bug ko try-catch mein lapetne se wo bug rehna band nahi karta; bas chhup jaata hai. Compiler inke baare mein chup isliye rehta hai: har mumkin bug pe catch maangna matlab duniya ki har line pe catch maangna.
In udaharanon mein se ek ke andar ek trap chhupa hua hai. ArithmeticException 1 / 0 pe aati hai - lekin sirf integers ke liye. Floating-point division throw karti hi nahi:
1/0 -> java.lang.ArithmeticException: / by zero
1.0/0 -> Infinity
0.0/0 -> NaN
total -> NaN
1.0 / 0 hai Infinity, 0.0 / 0 hai NaN, aur program bas chalta rehta hai. Nuksaan aakhri line mein hai: 100 + NaN phir bhi NaN hai, yaani ek kharab average chup-chaap poori report ko zeher kar deta hai aur kisi ko stack trace dikhta hi nahi. Ye is chapter ki theme ka chhota roop hai - crash aapko bata deta hai ki kuch galat hua; chup-chaap galat number nahi batata. Isi wajah se "zero se bhaag hamesha throw karta hai" ek galat jawab hai.
Checked exceptions - aur file I/O ka darwaza
| Exception | Kab aati hai |
|---|---|
IOException |
koi bhi file / stream / network read ya write fail ho jaaye |
FileNotFoundException |
IOException ki subclass - path maujood nahi ya padha nahi ja sakta |
SQLException |
database call fail ho gayi |
ClassNotFoundException |
Class.forName("...") ko class mili hi nahi |
InterruptedException |
soya ya intezaar karta hua thread interrupt ho gaya |
ParseException |
SimpleDateFormat date string padh nahi paaya |
In sab mein program apne se bahar kisi cheez se baat kar raha hai - disk, socket, database, doosra thread.
Yahi wo line hai jo baaki poore chapter ko samajh mein laati hai: gayab file programming ki galti nahi hai, wo duniya ka ek sach hai. Aapka code bilkul saaf ho sakta hai aur file phir bhi na ho - kisi insaan ne delete kar di, mount gir gaya, ya upload poora hua hi nahi. Kitni bhi savdhaani se code likhein, ye mumkin rehta hai - isliye Java aapko use chup-chaap nazarandaz karne nahi deta. IOException ke checked hone ki poori wajah yahi hai, aur isi wajah se is chapter ka doosra hissa, files aur streams, checked exceptions se bhara hua hai.
Checked exception handle karne ke theek DO tareeke
Java mein yahi ek jagah hai jahan "handle karna" ka matlab do options hain, ek nahi - aur interviewer aam taur pe dono ke naam sunna chahta hai.
1. Use catch kijiye - zimmedari aap yahin le rahe hain.
try {
return Files.readString(Path.of("config.txt"));
} catch (IOException e) {
return "default-config"; // file ke bina bhi mujhe pata hai kya karna hai
}
2. throws se declare kijiye - aap zimmedari se mana kar ke use upar bhej rahe hain.
String loadConfig() throws IOException {
return Files.readString(Path.of("config.txt")); // caller faisla kare
}
Teesra koi option nahi hai. Na aap use ignore kar sakte hain, na koi switch hai jo check band kar de. Agar dono mein se kuch nahi likha, to javac ruk jaata hai - unreported exception ... must be caught or declared to be thrown - aur class file banti hi nahi.
Dhyaan se: throws kuch handle nahi karta. Wo ek declaration hai, hal nahi. Wo wahi faisla call stack mein ek level upar sarka deta hai - aur agar har method use main tak declare karta rahe, to JVM stack trace chhaap kar program band kar deta hai.
To do mein se kaunsa? Ek sawaal poochhiye
Kya main is haalat ko yahin theek kar sakta hoon? Haan ->
catchkijiye, aur theek karne wala kaam kijiye: default use karein, retry karein, user ko asli message dikhayein. Nahi ->throwsse upar jaane dijiye, taaki jiske paas zyada context hai wo faisla kare.
Code ke andar gehre baithe ek DAO ko kya pata ki gayab config file pe program band hona chahiye ya default pe chalna chahiye - use declare kar ke aage badh jaana chahiye. Sabse upar wale startup code ko pata hota hai - use catch kar ke saaf message log karna chahiye aur theek se band ho jaana chahiye. Jis exception ka aap kuch kar hi nahi sakte use catch karna hi wo tareeka hai jisse asli failure chup-chaap gayab ho jaata hai.
Kab use karein: apni exception ko unchecked banayein (RuntimeException extend karke) jab wo programming bug batati ho ya aisi haalat ho jisse upar koi bhi ubhar nahi sakta - galat arguments, toota hua invariant, ya wo config value jo startup pe hi validate honi chahiye thi. Bug ke chaaron taraf catch likhwaane se kisi ka faayda nahi.
Kab NAHI use karein: use checked (Exception extend karke) tab hi banayein jab caller uski wajah se sach mein kuch alag kar sakta ho - download dobara try kare, cached file pe gir jaaye, user se doosra path maange. Agar aap wo recovery action naam nahi le paa rahe, to checked galat chunaav hai: aap bas har caller mein try-catch ka shor bhar rahe hain.
Trade-off: checked exceptions aapko compiler ki taraf se garanti dete hain ki failure case kisi ne bhula nahi, aur badle mein signature churn ka kharcha lete hain - ek throws jodne se das methods badal sakte hain. Isi kharche ki wajah se aaj ke frameworks jaise Spring aur Hibernate, aur zyadatar HTTP clients, apni checked exceptions ko unchecked mein lapet dete hain. Ye soch-samajh kar kiya gaya sauda hai, shortcut nahi: unhone saaf signatures ke badle compiler ki yaad-dihaani chhod di.
Wo trap jisme lagbhag har learner phasta hai
Integer.parseInt(null) - kya throw karegi? Lagbhag har koi NullPointerException bolta hai. Wo NumberFormatException hai, aur neeche practice section mein uska asli output hai. parseInt string ko dereference karti hi nahi; wo use validate karti hai aur "padhi nahi ja sakti" keh kar reject kar deti hai. Ye dono unchecked hain, isliye compiler ne kisi bhi tarah aapko aagah nahi kiya - aur bilkul isi wajah se sahi jaanne ka ek hi bharosemand tareeka hai: chala kar dekhna.
Standard definition (interview me bolo): A checked exception is any Throwable that is neither a RuntimeException nor an Error. The compiler requires every checked exception to be either caught in a try-catch block or declared in the method's throws clause; unchecked exceptions carry no such requirement, even though both kinds are thrown at runtime.
import java.io.FileReader;
import java.io.IOException;
public class Demo {
// Way 1 - CATCH: I can handle this situation right here
static String readOrDefault(String path) {
try (FileReader r = new FileReader(path)) {
return "file found";
} catch (IOException e) {
return "default value (" + e.getClass().getSimpleName() + ")";
}
}
// Way 2 - DECLARE: I cannot fix it, let the caller decide
static String readStrict(String path) throws IOException {
try (FileReader r = new FileReader(path)) {
return "file found";
}
}
public static void main(String[] args) {
System.out.println("A caught here = " + readOrDefault("nahi-hai.txt"));
try {
System.out.println("B declared = " + readStrict("nahi-hai.txt"));
} catch (IOException e) {
System.out.println("B declared = caller caught it: " + e.getClass().getSimpleName());
}
// Unchecked - the compiler asked us to write nothing at all
int[] marks = new int[3];
try {
System.out.println(marks[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("C unchecked = " + e);
}
}
}Project: CSV Report Loader
Ek college clerk ki table par 200 admission forms ka dher rakha hai aur bharne ke liye ek register. Form 3 par marks ki jagah number ke bajaye achha likha hai. Form 5 me marks ka column hai hi nahi. Kya wo poora dher kachre me daal kar ghar chala jaayega?
Nahi. Wo un do forms ko ek problem pile par rakh deta hai, baaki 198 register me chadha deta hai, aur principal ko do cheezein deta hai: bhara hua register, aur problem pile jisme har form par ek parchi lagi hai ki us form me kya galat tha.
Ab ek cheez badal dijiye. Wo aata hai aur register ki almari band hai, chaabi kisi ke paas nahi. Iske liye koi problem pile nahi hoti. Wo ruk jaata hai, aur shuru me hi, zor se, us ek aadmi ko bata deta hai jo chaabi dhoondh sakta hai.
Poora chapter isi ek table par baitha hai:
Ek kharab row recoverable hai, isliye aap use catch karke aage badhte hain. Missing file recoverable nahi hai, isliye aap use rukne dete hain.
Production me forms ka dher kisi doosri team ka export kiya hua CSV hota hai, aur wo kabhi saaf nahi hota. Jo loader pehli kharab row par mar jaata hai wo raat 2 baje failing nightly job ban jaata hai — 40,000 me se 3 rows import karke, aur ye list chhode bina ki galat kya tha. Jo loader kharab rows jhel leta hai wo 39,996 import kar deta hai aur un chaar ki report de deta hai jinhe wo use nahi kar paaya.
🌍 Real-world example: ek college results portal par marks sheet upload karta hai. Row 3 ke marks column me
not-a-numberlikha hai. Agar portal crash ho jaaye, clerk ko sirf "Upload failed" dikhta hai, use pata hi nahi chalta ki 400 rows me se kaunsi theek karni hai, aur wo wahi file dobara upload kar deta hai. Agar portal jitna load ho sakta hai load kar de, to use dikhta hai "396 loaded, 4 rejected — line 3: marks is not a number", wo do minute me chaar rows theek karta hai aur dobara upload kar deta hai. Data utna hi kharab, par din bilkul alag.
💡 Recoverable failure = wo failure jiske liye caller ke paas sach me koi kaam ka doosra raasta ho. Ek row skip karke baaki 199 import karna kaam ka hai. Ye dikhawa karna ki jo file padhi hi nahi gayi wo padh li gayi, kaam ka nahi hai. 💡
InvalidRowException= wo custom checked exception jo aap yahan likhenge. YeExceptionko extend karti hai aur fail hui row ka line number aur raw text apne saath le kar chalti hai. 💡 Cause = asli neeche waali exception (yahanNumberFormatException) jo aap apni exception ke constructor ko dete hain, taaki report ye bhi dikha sake ki parser ne asal me kis cheez par aitraaz kiya tha. 💡 Collect-and-report = har failure ko ekListme daalte jaana jabki loop chalta rahe, aur sabko ek saath aakhir me print karna — ek-ek karke beech me rukne ke bajaye.
Aap kya bana rahe hain
CsvReportLoader — ek hi file, koi library nahi, jo marks.csv ko try-with-resources ke andar padhti hai; ek row ko chaar alag wajahon se reject karti hai (blank line, columns ki galat ginti, non-numeric field, marks 0–100 ke bahar); har rejection ke baad chalti rehti hai; aakhir me batati hai kitni rows load hui, kitni reject hui aur kyun; aur agar file hai hi nahi to ek saaf message ke saath ruk jaati hai.
Step 0 — data file
Apni .java file ke saath marks.csv banaiye. Bilkul aise hi likhiye, kharab rows samet — kharab rows hi to poori baat hain:
id,name,marks
1,Aarav,88
2,Diya,not-a-number
3,Ishaan,76
4,Neha
5,Kabir,105
6,Meera,64
7,Rohan,abc,extra
8,Zoya,91
Line 6 sach me khaali hai; use khaali hi rehne dijiye. Lines header samet giniye, kyunki aapki report yahi line numbers quote karegi aur inhe us file se match karna hai jo koi insaan Excel me kholega.
Chaar theek rows aur paanch kharab: line 3 ke marks column me text hai, line 5 me do hi columns hain, line 6 blank hai, line 7 ke marks 105 hain, line 9 me chaar columns hain. Itni kharab file jaan-boojh kar banayi gayi hai, taaki har branch pehli hi baar chal jaaye.
Step 1 — file ko safely padhiye aur lines giniye
try (BufferedReader br = new BufferedReader(new FileReader("marks.csv"))) {
String line;
int lineNumber = 0;
while ((line = br.readLine()) != null) {
lineNumber++;
System.out.println(lineNumber + " : [" + line + "]");
}
} catch (IOException e) {
System.out.println("FATAL: " + e);
}
1 : [id,name,marks]
2 : [1,Aarav,88]
...
6 : []
...
10 : [8,Zoya,91]
In chhah lines me teen faisle pehle hi ho chuke hain:
- Reader ek resource hai, isliye wo bracket ke andar jaata hai.
brnormal exit par band hota hai,returnpar band hota hai, aur exception par bhi — aur agar khudclose()fail ho jaaye, to aapki asli exception phir bhi aap tak pahunchti hai, close ki failure suppressed ban kar us se judi hui. Haath se likhafinally { br.close(); }aapko close ki failure thama deta hai aur asli error kho deta hai. readLine()file khatam hone parnulldeta hai — throw nahi karta. Isi wajah sewhile ((line = br.readLine()) != null)sahi idiom hai, koi jugaad nahi.- Blank line
""ban kar aati hai,nullban kar nahi. Line 6 ne[]print kiya. "Empty string" ko kabhi end-of-file ka test mat banaiye.
Step 2 — aisi exception jo saboot saath le kar chale
Kharab row se "invalid" shabd se zyada kuch nikalna chahiye. Jo file theek karega use chahiye kaunsi line aur us par tha kya:
static class InvalidRowException extends Exception {
private final int lineNumber;
private final String rawLine;
InvalidRowException(String message, int lineNumber, String rawLine) {
this(message, lineNumber, rawLine, null);
}
InvalidRowException(String message, int lineNumber, String rawLine, Throwable cause) {
super(message, cause);
this.lineNumber = lineNumber;
this.rawLine = rawLine;
}
int getLineNumber() { return lineNumber; }
String getRawLine() { return rawLine; }
}
extends Exceptionise checked banata hai, aur yahan yahi sahi hai. Compiler har call ko rok dega jab tak koi ise catch na kare yathrowsdeclare na kare — aur aap yahi chahte hain, kyunki caller sach me recover kar sakta hai.- Do fields, kyunki handler unhe use karta hai. Line number ko
getMessage()me se string parsing karke nikaalna us din toot jaata hai jis din koi message ke shabd badal deta hai. - Do constructors, doosra sirf
causelene ke liye. Kuch rejections ke neeche asli exception hoti hai, kuch ke neeche nahi, isliye chhota constructornullke saath aage bhej deta hai.
Step 3 — parseRow, aur row ke kharab hone ke chaar tareeke
static Student parseRow(String line, int lineNumber) throws InvalidRowException {
if (line.trim().isEmpty()) {
throw new InvalidRowException("blank line", lineNumber, line);
}
String[] parts = line.split(",");
if (parts.length != 3) {
throw new InvalidRowException("expected 3 columns, found " + parts.length, lineNumber, line);
}
int id;
int marks;
try {
id = Integer.parseInt(parts[0].trim());
marks = Integer.parseInt(parts[2].trim());
} catch (NumberFormatException e) {
throw new InvalidRowException("id and marks must be numbers", lineNumber, line, e);
}
if (marks < 0 || marks > 100) {
throw new InvalidRowException("marks out of range: " + marks, lineNumber, line);
}
return new Student(id, parts[1].trim(), marks);
}
Chaar sample rows dene par ye print hota hai:
OK -> 1 Aarav 88
REJECTED -> line 2: id and marks must be numbers
raw = [2,Diya,not-a-number]
cause = java.lang.NumberFormatException: For input string: "not-a-number"
REJECTED -> line 3: expected 3 columns, found 2
raw = [4,Neha]
cause = null
REJECTED -> line 4: marks out of range: 105
raw = [5,Kabir,105]
cause = null
Pehle rejection ke paas cause hai aur baaki do ke paas null — aur ye farq laaparwahi nahi, imaandari hai. NumberFormatException sach me Integer.parseInt ne throw ki thi, aur uska message wo exact text batata hai jo parse nahi hua — jo aapka apna message nahi batata. Wo ek , e use bacha leta hai; comma hata dijiye aur getCause() hamesha ke liye null de dega, kyunki asli object catch hua, ignore hua aur garbage collect ho gaya. Baaki do rejections aapke apne rule the, kisi library ke nahi, isliye neeche jodne ko kuch tha hi nahi.
Do chhoti baatein. parts[0].trim() sajaawat nahi hai: Integer.parseInt("12 ") peeche waali space par throw karta hai, yaani comma ke baad ek space ek bilkul theek row ko reject kara deti. Aur marks < 0 || marks > 100 ek business rule hai, parsing rule nahi — 105 theek se parse hota hai, bas wo mumkin marks nahi hai. Asli loaders me dono tarah ke check hote hain, aur dono ka ghar wahi ek rejection path hai.
Step 4 — try loop ke ANDAR jaata hai
Yahi step tay karta hai ki project chalega ya nahi, aur ye sirf ek indentation level ki baat hai.
Andar waala try hata dijiye — InvalidRowException ko loop se bahar nikal jaane dijiye — aur poora run bas itna hai:
Exception in thread "main" CsvReportLoader$InvalidRowException: id and marks must be numbers
at CsvReportLoader.parseRow(CsvReportLoader.java:51)
at CsvReportLoader.load(CsvReportLoader.java:71)
at CsvReportLoader.main(CsvReportLoader.java:82)
Caused by: java.lang.NumberFormatException: For input string: "not-a-number"
at java.base/java.lang.Integer.parseInt(Integer.java:668)
at CsvReportLoader.parseRow(CsvReportLoader.java:49)
... 2 more
(Line numbers meri file ke hain, aur maine JDK ki do frames chhaant di hain.) Dhyaan dijiye ki yahan kya nahi hai: koi report hi nahi. Line 3 ki ek kharab row ne chaar theek rows aur chaar aur failure reports mita di, jo ab kisi ko kabhi nahi dikhengi. Trace me Step 3 ki chaining ka fayda zaroor dikhta hai — upar waali exception aapki layer ka naam hai, aur asli galti aakhri Caused by: block me baithi hai.
Ab try ko sirf us ek parseRow call ke aas-paas rakhiye, taaki catch while ke andar baithe:
try {
Student s = parseRow(line, lineNumber);
loaded++;
System.out.println("kept line " + lineNumber + " -> " + s);
} catch (InvalidRowException e) {
rejected.add("line " + e.getLineNumber() + ": " + e.getMessage());
System.out.println("skipped line " + lineNumber + " -> " + e.getMessage());
}
kept line 2 -> 1 Aarav 88
skipped line 3 -> id and marks must be numbers
kept line 4 -> 3 Ishaan 76
skipped line 5 -> expected 3 columns, found 2
skipped line 6 -> blank line
skipped line 7 -> marks out of range: 105
kept line 8 -> 6 Meera 64
skipped line 9 -> expected 3 columns, found 4
kept line 10 -> 8 Zoya 91
loaded=4 rejected=5
catch sirf apne try block ko khatam karta hai, us se bade kisi block ko nahi. try yahan ek hi statement chauda hai, isliye catch hote hi wo statement khatam hota hai aur while aage badh jaata hai. Skip-and-continue ke peeche bas yahi mechanism hai — na koi continue keyword, na koi flag.
Khud dekh lijiye: wahi try bahar khiska kar poore while ke aas-paas laga dijiye. Wahi file, wahi parser, sirf ek indentation level ka farq, aur report sikud kar rows loaded = 1 aur rows rejected = 1 reh jaati hai — lines 4 se 10 padhi hi nahi jaatin. try block ki chaudai ek design faisla hai, formatting nahi.
Step 5 — summary
load theek rows lautata hai aur caller ka diya hua rejected list bharta hai; main dono hisse print karta hai. Uska signature dekhiye: throws IOException. InvalidRowException andar hi handle hoti hai, IOException jaan-boojh kar nahi. Poora program aur uska asli output neeche code panel me hai; jin do lines ke liye ye poora project hai wo hain rows loaded = 4 aur rows rejected = 5, aur uske baad har rejection line number, wajah, cause (jahan ho) aur raw text bata deti hai. Ye aisi report hai jis par ek non-programmer bhi kaam kar sakta hai.
Step 6 — wo failure jise aap recover karne se mana kar dete hain
Wahi program aisi file par chalaiye jo hai hi nahi:
FATAL: cannot read nahi-hai.csv
java.io.FileNotFoundException: nahi-hai.csv (The system cannot find the file specified)
Koi report nahi, koi row nahi, koi average nahi — aur yahi sahi hai. Yahan "0 rows loaded" print karna nuksaandeh hota, kyunki "file me koi valid row nahi hai" aur "file hai hi nahi" ke liye output padhne waale ko bilkul alag fix karna padta hai.
Do footnotes. Bracket ke andar ka text operating system se aata hai, Java se nahi: is Windows machine par wo (The system cannot find the file specified) likhta hai, Linux par wahi exception (No such file or directory) print karti hai — kisi test me us text par assert mat kijiye. Aur exception ka naam API par depend karta hai: new FileReader(...) java.io.FileNotFoundException throw karta hai, jabki Files.newBufferedReader(Path.of("marks.csv")) usi missing file par java.nio.file.NoSuchFileException throw karta hai. IOException catch karna dono ko cover kar leta hai, aur yahi ek achhi wajah hai yahan parent ko catch karne ki.
Catch karke aage tab badhiye jab caller ke paas sach me koi aisa raasta ho jo rukne se zyada kaam ka ho: bahut si rows me se ek kharab row, ek batch me ek kharab record. Sawaal ye nahi hai ki "kya main catch block likh sakta hoon" — likh to hamesha sakte hain. Sawaal ye hai ki "aage karne layak kuch hai bhi?" Rukne tab dijiye jab aisa kuch na ho: input file gayab, startup config gayab, koi invariant toota hua. Unhe catch karke chalte rehna aisa program banata hai jo kuch kiye bina success bata deta hai, aur ye crash se bhi bura hai, kyunki crash kam se kam kisi ko bata to deta hai. Aur jab rukein to saaf rukein — khaali catch block us FATAL line ka ulta hai jis par koi raat 2 baje kaam kar sake.
Ek imaandar limitation
String.split(",") CSV parser nahi hai aur ye lesson aisa dikhawa bhi nahi kar raha. Asli CSV me quoted fields ke andar comma aa sakta hai, aur aakhir ka khaali column bas gayab ho jaata hai:
[5,Kabir,] -> 2 parts
[1,"Kumar, Aarav",88] -> 4 parts
Ye loader dono ko "wrong column count" kehta hai — ek aisi row ke liye galat wajah jo shayad theek hi hai. Asli files ke liye CSV library use kijiye (OpenCSV, Apache Commons CSV). Aapne jo exception handling banayi hai wo nahi badalti; sirf splitting badalti hai.
Khud try kijiye
- Ek duplicate id rule jodiye — dekhe ja chuke ids ka
Set<Integer>rakhiye aur doosri baar aane par usiInvalidRowExceptionse reject kijiye. Exception class me ek shabd bhi nahi badalna padega — isi liye custom exception rakhna faydemand hota hai. - Program ko non-zero exit karwaiye jab kuch bhi reject hua ho, taaki koi shell script adhoora import pakad sake. Yaad rakhiye
System.exitfinallyblocks nahi chalata. - Ek rejection limit jodiye: 20 kharab rows ke baad ruk kar throw kar dijiye, is aadhaar par ki shayad ye file hi galat hai. Yahi dilchasp beech ka case hai — ek-ek karke recoverable, thok me unrecoverable.
new FileReader(fileName)koFiles.newBufferedReader(Path.of(fileName))se badal kar missing-file case dobara chalaiye. Exception ka naamNoSuchFileExceptionho jaata hai aur aapkacatch (IOException e)phir bhi use pakad leta hai.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CsvReportLoader {
// CHECKED: a bad row is something the caller can genuinely act on - skip it and carry on.
static class InvalidRowException extends Exception {
private final int lineNumber;
private final String rawLine;
InvalidRowException(String message, int lineNumber, String rawLine) {
this(message, lineNumber, rawLine, null);
}
InvalidRowException(String message, int lineNumber, String rawLine, Throwable cause) {
super(message, cause);
this.lineNumber = lineNumber;
this.rawLine = rawLine;
}
int getLineNumber() { return lineNumber; }
String getRawLine() { return rawLine; }
}
static class Student {
final int id;
final String name;
final int marks;
Student(int id, String name, int marks) {
this.id = id;
this.name = name;
this.marks = marks;
}
@Override public String toString() { return id + " " + name + " " + marks; }
}
static Student parseRow(String line, int lineNumber) throws InvalidRowException {
if (line.trim().isEmpty()) {
throw new InvalidRowException("blank line", lineNumber, line);
}
String[] parts = line.split(",");
if (parts.length != 3) {
throw new InvalidRowException("expected 3 columns, found " + parts.length, lineNumber, line);
}
int id;
int marks;
try {
id = Integer.parseInt(parts[0].trim());
marks = Integer.parseInt(parts[2].trim());
} catch (NumberFormatException e) {
throw new InvalidRowException("id and marks must be numbers", lineNumber, line, e);
}
if (marks < 0 || marks > 100) {
throw new InvalidRowException("marks out of range: " + marks, lineNumber, line);
}
return new Student(id, parts[1].trim(), marks);
}
// Recoverable failures land in rejected. An unreadable file is NOT recoverable here,
// so IOException is declared, not caught - it must reach main and stop the program.
static List<Student> load(String fileName, List<String> rejected) throws IOException {
List<Student> loaded = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
int lineNumber = 0;
while ((line = br.readLine()) != null) {
lineNumber++;
if (lineNumber == 1) {
continue; // header row
}
try {
loaded.add(parseRow(line, lineNumber));
} catch (InvalidRowException e) {
String reason = "line " + e.getLineNumber() + ": " + e.getMessage();
if (e.getCause() != null) {
reason = reason + " (cause: " + e.getCause() + ")";
}
rejected.add(reason + " raw=[" + e.getRawLine() + "]");
}
}
}
return loaded;
}
public static void main(String[] args) {
String fileName = args.length > 0 ? args[0] : "marks.csv";
List<String> rejected = new ArrayList<>();
List<Student> loaded;
try {
loaded = load(fileName, rejected);
} catch (IOException e) {
System.out.println("FATAL: cannot read " + fileName);
System.out.println(" " + e);
return;
}
int total = 0;
System.out.println("== REPORT: " + fileName + " ==");
for (Student s : loaded) {
System.out.println(" " + s);
total += s.marks;
}
System.out.println("rows loaded = " + loaded.size());
System.out.println("rows rejected = " + rejected.size());
for (String r : rejected) {
System.out.println(" " + r);
}
if (!loaded.isEmpty()) {
System.out.println("average marks = " + (total / (double) loaded.size()));
}
}
}Exceptions aur File I/Ointerview questions & answers
10 sample questions below — 203+ in the full bank inside.
Custom exception mein kaun se constructor hone chahiye, aur wahi kyun?
Kam se kam (String message) aur (String message, Throwable cause), dono sirf super(...) call karte hue. Doosra wala shauk nahi hai -- cause store hone ka yahi ek aam raasta hai, isliye jo class sirf message wala constructor deti hai wo chupke se har aane wale caller ke liye chaining namumkin kar deti hai. Ek purana raasta initCause(e) bhi hai, par wo Java 1.4 se pehle ka bacha hua tareeka hai, jab Throwable ke paas cause lene wala constructor nahi tha.
In simple terms: Do constructors ko delivery form ke do khaane samajhiye: ek wo jo aap customer ko batana chahte hain, aur doosra wo asli damaged-goods parchi jise aap peeche staple karte hain. Agar form mein doosra khaana hai hi nahi, to koi kitna bhi chaahe, kuch staple kar hi nahi sakta. Ek run se ye thos ho jaata hai: sirf OnlyMessage(String message) declare karne wali class par new OnlyMessage("user load failed", e) compile hi nahi hota -- javac kehta hai constructor cannot be applied to given types, required: String, found: String,NumberFormatException.
Runtime exception kya hoti hai? Do udaharan dijiye.
Runtime exception wo hai jo java.lang.RuntimeException ke neeche baithi hai, aur isi wajah se wo unchecked hai: compiler aapse kuch nahi maangta, na catch na throws. Do rozmarra ke udaharan hain NullPointerException, jo null reference pe method call karne pe aati hai, aur ArrayIndexOutOfBoundsException, jo length 3 wale array pe marks[5] karne pe aati hai. Dono ka matlab lagbhag hamesha yahi hota hai ki aapke apne code mein bug hai, isliye ilaaj code theek karna hai, use try-catch mein lapetna nahi.
In simple terms: Bahar jaate waqt chaabi mez pe chhod dena sochiye. Wo aapki apni galti hai, uske liye building ka koi niyam ban hi nahi sakta, aur gate pe khada guard iske liye aapko kabhi nahi rokta -- bas aadat sudharni padti hai. Thos misaal: int[] marks = new int[3]; System.out.println(marks[5]); javac ne ek shabd kahe bina compile kar diya aur wo sirf chalne pe fail hua: java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3.
Custom exception kya hoti hai, aur aap ise likhenge hi kyun?
Custom exception aapki khud ki likhi hui ek class hai jo Exception ya RuntimeException ko extend karti hai, taaki failure library ke naam ke bajaye aapki application ke naam se aaye. Ise tab likhte hain jab caller ko is failure ko baaki failures se alag pehchanna ho -- jaise ek import jise kharab rows ko missing file se alag ginna hai, ya ek payment layer jise declined card aur gateway timeout mein fark karna hai. Exception extend karne se ye checked ban jaati hai, RuntimeException extend karne se unchecked, aur bas yahi ek shabd poora faisla hai.
In simple terms: Ek hospital lab sochiye. Technician ko crack tube milta hai aur wo corridor mein chilla sakta hai 'tube crack hai!' -- baat sahi hai, aur patient ke saamne khadi receptionist ke liye bekaar hai. Reception ko chahiye 'patient 42 ka test nahi ho paaya'. Ek hi ghatna, do zubaanein: ek plumbing bataati hai, doosri business. Thos misaal: Integer.parseInt NumberFormatException phenkta hai, jo candidates ya rows ke baare mein kuch nahi kehta; import service use catch karke apni InvalidRowException("row 47 is broken", 47, e) phenkti hai, jise screen sach mein dikha sakti hai.
Dikhaiye ki aap ek custom exception class asal mein kaise likhenge.
Sirf teen cheezein, isse zyada kuch nahi: Exception ya RuntimeException ko extend kijiye, ek (String message) constructor aur ek (String message, Throwable cause) constructor dijiye jo dono bas super(...) call karein, aur field tabhi jodiye jab handler ko us par kuch karna ho. Khaali body bilkul legal hai aur zyadatar custom exceptions koi behaviour jodti hi nahi. Class ka naam Exception par khatam kijiye -- ye convention hai, compiler ka rule nahi, par har reviewer yahi ummeed karta hai.
In simple terms: Ye logon ki soch se chhota kaam hai -- class likhne se zyada ek form bharne jaisa. Jaise: class DataAccessException extends RuntimeException { DataAccessException(String message) { super(message); } DataAccessException(String message, Throwable cause) { super(message, cause); } }. Poori class bas itni hai. rowNumber jaisa field ki jagah sirf isliye banti hai kyunki caller skipped rows ginta hai; agar koi handler use istemaal hi nahi karta to wo bas extra code hai.
Kya throws sach mein exception ko handle karta hai?
Nahi. throws method ke signature mein likha ek declaration hai, hal nahi. Wo compiler aur caller ko batata hai ki ye method ye exception aapko wapas de sakta hai aur aap sambhaliye. Yahan kuch catch nahi hota, kuch theek nahi hota -- wahi faisla bas call stack mein ek level upar sarak jaata hai. Aur agar har method use main tak declare karta rahe, to JVM stack trace System.err pe chhaap kar program band kar deta hai.
In simple terms: Gate pe parcha likh dene se aap sookhe nahi reh jaate. Uska sirf itna matlab hai ki upar kisi ne bheege hue aapko sambhalna maan liya hai. Thos misaal: static String readStrict(String path) throws IOException { ... } apni body mein kahin catch ke bina compile ho gaya, aur phir compiler ne uski jagah call site ko zimmedar maana -- us call ko apne try-catch ke andar baithna pada, aur run mein chhapa B declared = caller caught it: FileNotFoundException.
Checked exception handle kaise karte hain, aur kitne tareeke hain?
Theek do. Ya to use try-catch mein catch kijiye aur zimmedari wahin le lijiye, ya method signature pe throws se declare kar ke caller ko faisla karne dijiye. Teesra koi option nahi hai, use ignore karne ka raasta nahi hai aur koi switch nahi hai jo check band kar de -- dono mein se kuch na likhein to javac ruk jaata hai, unreported exception ... must be caught or declared to be thrown, aur class file banti hi nahi. Aur dhyaan rahe throws kuch handle nahi karta; wo bas wahi faisla call stack mein ek level upar sarka deta hai.
In simple terms: Gate ka guard theek do cheezein maanta hai: ya aapke haath mein chhata ho, ya aapne parcha likh diya ho ki jo intezaar kar raha hai use pata hai aap bheege pahunch sakte hain. Dono mein se kuch nahi, to wo gate kholta hi nahi. Code mein pehla tareeka hai try { return Files.readString(Path.of("config.txt")); } catch (IOException e) { return "default-config"; } aur doosra hai String loadConfig() throws IOException { ... }.
Asal mein kya tay karta hai ki exception checked hai ya unchecked -- iske liye koi keyword hai?
Na koi keyword hai na koi annotation. Ye sirf isse tay hota hai ki class Throwable ke tree mein kahan baithi hai. RuntimeException ke neeche sab unchecked, Error ke neeche sab unchecked, aur Exception ke neeche baaki sab checked. Bas itna hi poora rule hai, aur isi wajah se aap kisi bhi exception ke baare mein ye sawaal sirf uska parent chain chal kar jawab de sakte hain.
In simple terms: Ye waise hi hai jaise flat kis manzil pe hai -- darwaze pe kuch likha nahi hota, sirf pata hi bata deta hai. Thos misaal: NumberFormatException sunne mein bilkul checked lagti hai, par uska chain hai NumberFormatException -> IllegalArgumentException -> RuntimeException, isliye wo unchecked hai. JDK 17 pe new NumberFormatException("x") instanceof RuntimeException chalaya to true aaya.
Checked exceptions ke do udaharan dijiye.
IOException, aur uski subclass FileNotFoundException, wo hain jinse sabse pehle saamna hota hai; doosri classic hai SQLException. ClassNotFoundException, InterruptedException aur ParseException bhi checked hain. Definition ye hai ki checked exception wo har Throwable hai jo na RuntimeException hai na Error, isliye har caller ko ya to use catch karna hoga ya declare. In sab mein ek baat common hai: program apne se bahar kisi cheez se baat kar raha hai -- disk, database, socket, doosra thread.
In simple terms: Baarish aapki galti nahi hai. Wo bahar ki duniya ka sach hai, kisi bhi din ho sakti hai chahe aap kitne hi savdhaan hon, isliye building ka uske liye ek niyam hai: chhata, ya likha hua parcha, do mein se ek. Thos misaal: bina kisi handling ke new FileReader("nahi-hai.txt") likhne pe javac wahin ruk gaya: unreported exception FileNotFoundException; must be caught or declared to be thrown.
Error checked hoti hai ya unchecked?
Unchecked. OutOfMemoryError aur StackOverflowError Error ke neeche baithi hain, aur compiler unke baare mein kuch nahi maangta -- na catch na throws. Interview mein ye baat dhyaan se kehni chahiye: unchecked ka matlab RuntimeException ke neeche hona nahi hai. Error unchecked ki doosri shaakha hai, aur wo JVM level ki wo failures hain jinse ubharne ki aapse ummeed hi nahi ki jaati.
In simple terms: Chaabi bhoolna aapki galti hai aur baarish duniya ki, par building mein aag lagna teesri hi cheez hai -- gate ka koi niyam kaam nahi aata, bas bahar nikalna hota hai. Thos misaal: tree mein Throwable do hisson mein batta hai, Error (unchecked) aur Exception, aur Exception ka sirf wahi hissa checked hai jo RuntimeException se bahar hai. Isi wajah se aap kabhi catch (OutOfMemoryError e) nahi likhte aur javac kabhi maangta bhi nahi.
Maine class NoCtor extends RuntimeException { } likha aur phir throw new NoCtor("user load failed"). Ye compile hoga?
Nahi. Constructors inherit nahi hote, isliye khaali body wali class ke paas sirf implicit no-argument constructor hota hai, aur usme message bhejna compile error hai. javac kehta hai: constructor NoCtor in class NoCtor cannot be applied to given types; required: no arguments, found: String. Khaali body legal hai, par jis pal aapko message chahiye, us pal wo constructor khud declare karna padega aur super(message) se upar bhejna padega.
In simple terms: Class inherit karna dukaan virasat mein milne jaisa hai -- shelves aur till mil jaate hain, purane maalik ke order form nahi. Throwable ka (String) wala roop wahi ek order form hai: upar maujood hai, par aapki class use apne callers ko khud-ba-khud nahi deti. NoCtor(String message) { super(message); } likh dijiye aur wahi throw compile ho jaata hai.
193+ more Exceptions aur File I/O questions inside
Create a free account to read the full question bank, learn every topic, and practise with an AI mock interview.
Unlock all questions — freeReady to practise Exceptions aur File I/O?
Unlock every topic free, then face an AI interviewer that asks follow-ups and grades your answers.