Throw, Throws; Try, Catch and Finally

throw exception ને raise કરે છે, throws તેને method પર declare કરે છે, try/catch તેને handle કરે છે અને finally ગમે તે થાય તો પણ run થાય છે: BookBridge ના crash ને message માં turn કરતી full grammar.

11 min read · 9 cards · 2 checks

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


Theory

પાંચ keywords, એક working desk

Last lesson એ incident report લખ્યું: OverdueException. હવે desk એ actually તેને use કરવું જોઈએ.

આપણે જે flow જોઈએ છે: return-desk method overdue case ને detect કરે છે અને report ને raise કરે છે; તે તેના signature પર announce કરે છે કે આવા reports escape થઈ શકે છે; caller risky call ને wrap કરે છે, report ને handle કરે છે, અને register જે કંઈ થયું હોય તેનાથી regardless properly closes થાય છે.

Java એ 5 duties ને spell કરે છે: throw, throws, try, catch, finally. એક listing એ બધા ને show કરે છે.

Practical

એક desk માં complete 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) ને calls કરે છે
  • 20 > 14, એટલે throw fire થાય છે: checkReturn instantly stop થાય છે; તેની remaining line ક્યારેય run નથી થતી
  • exception caller પાસે flies back કરે છે; try block ની rest skipped થાય છે (એટલે "This line never runs")
  • catch (OverdueException e) match થાય છે, Caught: Overdue by 20 days print કરે છે
  • finally run થાય છે: Register closed

daysLate = 5 સાથે instead: try normally complete થાય છે, catch skip થાય છે, અને finally હજુ પણ run થાય છે.

Formula

throw vs throws (1-mark classic)

throw: method ની અંદર 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 હંમેશા runs કરે છે, D ઉમેરે છે. 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; સાથે ends થાય છે અને તેનું finally "closing" print કરે છે. tap કરતા પહેલા: શું "closing" appear થાય છે, અથવા return પહેલા exit થાય છે?

Show the answer

"closing" appear થાય છે. finally run થાય છે even જ્યારે try block return કરે છે, અને even જ્યારે exception flying હોય: Java pending return ને hold કરે છે, finally ને execute કરે છે, પછી return ને complete કરે છે. એ guarantee એ finally નું whole purpose છે: cleanup (files, registers, connections ને closing) જે દરેક exit path પર happen થવું જોઈએ. એકમાત્ર escape જે તે survive નથી કરી શકતો એ System.exit() છે, જે JVM ને itself kill કરે છે. exam phrasing: finally run થાય છે whether exception occur થાય છે કે નહીં.

Watch out

catch જે ક્યારેય run નથી કરી શકતો

multiple catch blocks ને child first, parent last order કરો:

catch (Exception e) { ... }

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

compile નથી થતું: Exception already દરેક OverdueException ને swallow કરે છે, એટલે બીજો catch dead code છે અને javac કહે છે કે exception has already been caught. specific handler ને first મૂકો, general safety net ને last. અને ક્યારેય empty catch block ન લખો: report ને silently swallow કરવો crash થી worse છે.

Theory

desk pattern, everywhere

આ shape (risky call in try, specific catch, cleanup in finally) exam-only નથી: એ રીત છે જે BookBridge Tuesday ના "12x" ને પણ survive કરે છે, parseInt ની આસપાસ NumberFormatException ને catch કરીને અને die કરવાને બદલે re-asking કરીને. તમે same grammar ને BCA504 ના PHP cousin માં file reads ને wrap કરતા, ADO.NET (BCA404 Unit 5) માં database calls ને, અને very next unit માં thread interruptions ને meet કરશો. jump ને once શીખો; તે same jump છે જે તમે આ પછી દરેક language ને touch કરો તેમાં.

Summary

Key takeaways

  • throw method ની અંદર એક exception object ને raise કરે છે; throws signature પર declare કરે છે કે શું escape થઈ શકે છે.
  • try risky code ને wrap કરે છે; throw પર, try ની rest skip થાય છે અને control matching catch પર jump કરે છે.
  • finally હંમેશા runs કરે છે: normal completion, exception, even pending return; ફક્ત System.exit એને prevent કરે છે.
  • Trace pattern: A, jump, C, D: શું threw, શું skip થયું, શું handle કર્યું, શું હંમેશા ran.
  • multiple catches child ને parent પહેલા મૂકો, અથવા parent later catches ને unreachable બનાવે છે (compile error).
  • Empty catch blocks problems ને hide કરે છે; 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