Throw, Throws; Try, Catch and Finally

throw exception raise करता है, throws इसे method पर declare करता है, try/catch इसे handle करता है और finally चाहे कुछ भी हो run होता है: पूरी grammar जो BookBridge के crash को एक message में बदल देती है।

11 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

पाँच Keywords, एक Working Desk

पिछले lesson ने incident report लिखी: OverdueException। अब desk को इसे असल में इस्तेमाल करना है।

वह flow जो हम चाहते हैं: return-desk method overdue case detect करता है और report raise करता है; यह अपने signature पर announce करता है कि ऐसी reports इससे escape हो सकती हैं; caller risky call को wrap करता है, report को handle करता है, और register properly बंद होता है चाहे कुछ भी हुआ हो।

Java उन 5 duties को spell करता है: throw, throws, try, catch, finally। एक listing इन सबको दिखाती है।

Practical

एक Desk में पूरी Grammar

class OverdueException extends Exception {
    OverdueException(String msg) { super(msg); }
}

public class ReturnDesk {
    static void checkReturn(int daysLate) throws OverdueException {
        if (daysLate > 14) {
            throw new OverdueException("Overdue by " + daysLate + " days");
        }
        System.out.println("Returned within limit");
    }

    public static void main(String[] args) {
        try {
            checkReturn(20);
            System.out.println("This line never runs");
        } catch (OverdueException e) {
            System.out.println("Caught: " + e.getMessage());
        } finally {
            System.out.println("Register closed");
        }
    }
}

Theory

Jump को Follow कीजिए

daysLate = 20 के साथ run trace कीजिए:

  • try शुरू होता है, checkReturn(20) call करता है
  • 20 > 14, तो throw fire होता है: checkReturn instantly रुक जाता है; इसकी बाकी line कभी run नहीं होती
  • exception वापस caller की तरफ़ उड़ता है; try block का बाकी हिस्सा skip होता है (इसीलिए "This line never runs")
  • catch (OverdueException e) match करता है, print करता है Caught: Overdue by 20 days
  • finally run होता है: Register closed

daysLate = 5 के साथ instead: try normally complete होता है, catch skip होता है, और finally फिर भी run होता है।

Formula

throw बनाम throws (1-Mark Classic)

throw: एक method के INSIDE एक statement जो exactly एक exception object raise करता है, right now।

throw new OverdueException("...");

throws: method signature पर एक clause जो declare करता है क्या escape हो सकता है, हर caller को prepare रहने की warning देते हुए।

static void checkReturn(int d) throws OverdueException

Exam के लिए memory line: throw इसे करता है, throws इसे declare करता है। एक act करता है, दूसरा announce करता है।

Quiz

try { System.out.print("A "); int x = 5 / 0; System.out.print("B "); } catch (ArithmeticException e) { System.out.print("C "); } finally { System.out.print("D"); } क्या print होता है?

  1. A B C D
  2. A C D
  3. A C
  4. A D
Show the answer

A C D

A पहले print होता है। फिर 5 / 0 ArithmeticException throw करता है, तो B skip हो जाता है: execution throwing line से सीधे matching catch पर jump करता है, C print करते हुए। finally हमेशा run होता है, D add करते हुए। Option A भूल जाता है jump B skip करता है। Option C भूल जाता है finally unconditional है। Option D imagine करता है catch match नहीं करता, पर ArithmeticException exactly वह है जो integer division by zero throw करता है। Result: A C D।

Think first

क्या finally return को Beat करता है?

एक method का try block return 1; से खत्म होता है और इसकी finally "closing" print करती है। Tap करने से पहले: क्या "closing" appear होता है, या return पहले exit हो जाता है?

Show the answer

"closing" appear होता है। finally तब भी run होता है जब try block return करता है, और तब भी जब एक exception उड़ रहा हो: Java pending return hold करता है, finally execute करता है, फिर return complete करता है। वह guarantee finally का पूरा purpose है: cleanup (files, registers, connections बंद करना) जो हर EXIT path पर होना चाहिए। एकमात्र escape जिसे यह survive नहीं कर सकता System.exit() है, जो JVM को खुद kill कर देता है। Exam phrasing: finally run होता है चाहे exception हो या न हो।

Watch out

वह Catch जो कभी Run नहीं हो सकता

Multiple catch blocks को child पहले, parent आख़िर में order कीजिए:

catch (Exception e) { ... }

catch (OverdueException e) { ... } // unreachable!

Compile नहीं होता: Exception पहले ही हर OverdueException swallow कर लेता है, तो दूसरा catch dead code है और javac कहता है exception पहले ही catch हो चुका है। Specific handler पहले रखिए, general safety net आख़िर में। और कभी एक empty catch block मत लिखिए: report को silently swallow करना crash से भी worse है।

Theory

Desk Pattern, हर जगह

यह shape (try में risky call, specific catch, finally में cleanup) सिर्फ़ exam के लिए नहीं है: BookBridge Tuesday के "12x" को भी इसी तरह survive करता है, parseInt के आस-पास NumberFormatException catch करके और मरने के बजाय फिर से पूछकर। आप यही grammar BCA504 के PHP cousin में file reads wrap करते हुए, ADO.NET (BCA404 Unit 5) में database calls, और बिल्कुल अगली unit में thread interruptions में मिलेंगे। Jump एक बार सीखिए; यह हर language में same jump है जिसे आप इसके बाद touch करते हैं।

Summary

Key takeaways

  • throw एक method के अंदर एक exception object raise करता है; throws signature पर declare करता है क्या escape हो सकता है।
  • try risky code wrap करता है; एक throw पर, try का बाकी हिस्सा skip होता है और control matching catch पर jump करता है।
  • finally हमेशा run होता है: normal completion, exception, यहाँ तक कि एक pending return; सिर्फ़ System.exit इसे रोकता है।
  • Trace pattern: A, jump, C, D: क्या thrown हुआ, क्या skip हुआ, क्या handle हुआ, क्या हमेशा run हुआ।
  • Multiple catches child को parent से पहले जाते हैं, वरना parent बाद वाले catches को unreachable बना देता है (compile error)।
  • Empty catch blocks problems छुपाते हैं; handle या log कीजिए, कभी swallow मत कीजिए।
  • Memory hook: throw इसे करता है, throws इसे declare करता है, finally इसे survive करता है।

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Basic Concepts of Strings and Exceptions

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Throw, Throws; Try, Catch and Finally · Java Programming Language · Gri-Learn