<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aditya Harendra Mall on Medium]]></title>
        <description><![CDATA[Stories by Aditya Harendra Mall on Medium]]></description>
        <link>https://medium.com/@adityaharendramall?source=rss-826dae311f2b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uMNDTi80B8fqJiixTc6Lng.jpeg</url>
            <title>Stories by Aditya Harendra Mall on Medium</title>
            <link>https://medium.com/@adityaharendramall?source=rss-826dae311f2b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:58:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adityaharendramall/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[3. Abstract Factory Pattern]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@adityaharendramall/3-abstract-factory-pattern-7fa700c8b000?source=rss-826dae311f2b------2"><img src="https://cdn-images-1.medium.com/max/1536/1*60o8IwoywHqwsu00VhYY8w.png" width="1536"></a></p><p class="medium-feed-snippet">Definition</p><p class="medium-feed-link"><a href="https://medium.com/@adityaharendramall/3-abstract-factory-pattern-7fa700c8b000?source=rss-826dae311f2b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@adityaharendramall/3-abstract-factory-pattern-7fa700c8b000?source=rss-826dae311f2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fa700c8b000</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[abstract-factory-pattern]]></category>
            <dc:creator><![CDATA[Aditya Harendra Mall]]></dc:creator>
            <pubDate>Fri, 18 Jul 2025 11:29:01 GMT</pubDate>
            <atom:updated>2025-07-18T11:29:01.758Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[3. Implementing Runnable Interface]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@adityaharendramall/3-implementing-runnable-interface-82811a10d7ee?source=rss-826dae311f2b------2"><img src="https://cdn-images-1.medium.com/max/1024/1*krTitnAA_xqiyq9Ro5dPqQ.png" width="1024"></a></p><p class="medium-feed-snippet">Topics Covered</p><p class="medium-feed-link"><a href="https://medium.com/@adityaharendramall/3-implementing-runnable-interface-82811a10d7ee?source=rss-826dae311f2b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@adityaharendramall/3-implementing-runnable-interface-82811a10d7ee?source=rss-826dae311f2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/82811a10d7ee</guid>
            <category><![CDATA[runnable-interface]]></category>
            <category><![CDATA[runnable]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Aditya Harendra Mall]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 17:16:37 GMT</pubDate>
            <atom:updated>2025-07-17T17:16:37.564Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[2. Design Patterns — Factory Pattern]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@adityaharendramall/2-design-patterns-factory-pattern-97820cbb2637?source=rss-826dae311f2b------2"><img src="https://cdn-images-1.medium.com/max/1024/1*k31_vA2wNtYVOQBQSmK1-Q.png" width="1024"></a></p><p class="medium-feed-snippet">Topics Covered</p><p class="medium-feed-link"><a href="https://medium.com/@adityaharendramall/2-design-patterns-factory-pattern-97820cbb2637?source=rss-826dae311f2b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@adityaharendramall/2-design-patterns-factory-pattern-97820cbb2637?source=rss-826dae311f2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/97820cbb2637</guid>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[factory-design-pattern]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Aditya Harendra Mall]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 00:38:26 GMT</pubDate>
            <atom:updated>2025-07-17T00:38:26.945Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[1. Design Pattern — Singleton]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@adityaharendramall/1-design-pattern-singleton-50aa634c9a1b?source=rss-826dae311f2b------2"><img src="https://cdn-images-1.medium.com/max/1024/1*NB0x4WKniunZx-4K2WR53Q.png" width="1024"></a></p><p class="medium-feed-snippet">&#x1F9FE; Singleton Pattern&#x200A;&#x2014;&#x200A;Table of Contents</p><p class="medium-feed-link"><a href="https://medium.com/@adityaharendramall/1-design-pattern-singleton-50aa634c9a1b?source=rss-826dae311f2b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@adityaharendramall/1-design-pattern-singleton-50aa634c9a1b?source=rss-826dae311f2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/50aa634c9a1b</guid>
            <category><![CDATA[singleton]]></category>
            <category><![CDATA[singleton-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Aditya Harendra Mall]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 23:14:26 GMT</pubDate>
            <atom:updated>2025-07-17T00:40:57.879Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[2. Ways to Define a Thread in Java — Extending Thread Class]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@adityaharendramall/2-ways-to-define-a-thread-in-java-extending-thread-class-5ca6b8b00e1a?source=rss-826dae311f2b------2"><img src="https://cdn-images-1.medium.com/max/1024/1*5O4Mpyt092QGtAbQ8VdI9g.png" width="1024"></a></p><p class="medium-feed-snippet">&#x1F9F5; Ways to Define a Thread&#x200A;&#x2014;&#x200A;Summary of Covered Topics:</p><p class="medium-feed-link"><a href="https://medium.com/@adityaharendramall/2-ways-to-define-a-thread-in-java-extending-thread-class-5ca6b8b00e1a?source=rss-826dae311f2b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@adityaharendramall/2-ways-to-define-a-thread-in-java-extending-thread-class-5ca6b8b00e1a?source=rss-826dae311f2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ca6b8b00e1a</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[core-java]]></category>
            <dc:creator><![CDATA[Aditya Harendra Mall]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 10:28:39 GMT</pubDate>
            <atom:updated>2025-07-16T10:28:39.145Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[1. Introduction to Threads in Java]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@adityaharendramall/introduction-to-threads-in-java-9a0829879242?source=rss-826dae311f2b------2"><img src="https://cdn-images-1.medium.com/max/1024/1*H_xB46xj6u0cwpeN4XhQPw.png" width="1024"></a></p><p class="medium-feed-snippet">&#x1F4DA; Syllabus Covered:</p><p class="medium-feed-link"><a href="https://medium.com/@adityaharendramall/introduction-to-threads-in-java-9a0829879242?source=rss-826dae311f2b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@adityaharendramall/introduction-to-threads-in-java-9a0829879242?source=rss-826dae311f2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a0829879242</guid>
            <category><![CDATA[core-java]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Aditya Harendra Mall]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 06:14:22 GMT</pubDate>
            <atom:updated>2025-07-16T10:29:33.658Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Core Java — Exceptional Handling — 09 — try with resources, multi catch block]]></title>
            <link>https://medium.com/@adityaharendramall/core-java-exceptional-handling-09-try-with-resources-multi-catch-block-c1e396b41c0f?source=rss-826dae311f2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1e396b41c0f</guid>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[core-java]]></category>
            <category><![CDATA[try-with-resources]]></category>
            <dc:creator><![CDATA[Aditya Harendra Mall]]></dc:creator>
            <pubDate>Wed, 19 Mar 2025 17:46:59 GMT</pubDate>
            <atom:updated>2025-05-09T09:26:58.089Z</atom:updated>
            <content:encoded><![CDATA[<h3>Core Java — Exceptional Handling — 09 — try with resources, multi catch block</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RJqXjfGNa6-x1hV7evICBw.png" /></figure><blockquote><strong><em>Topics covered in this article</em></strong><em><br>1. </em>Java 1.7 Enhancements in Exception Handling<br>2. <strong>Before Java 1.7 (Manual Resource Handling)<br>3. </strong><strong><em>try-with-resources</em> (Automatic Resource Management)<br>3.1. </strong>Case 01: Declaring Multiple Resources in try-with-resources<br>3.1.1. <strong>What is an </strong><strong><em>AutoCloseable</em> Resource?<br>3.2. </strong>Case 02: All Resource Variables Are Implicitly final<br>3.3.Case 03: try-with-resources Can Exist Without catch or finally<br>4. Multi-Catch Block<br>4.1. <strong>Before Java 1.7 (Multiple </strong><strong>catch Blocks Required)<br>4.2. </strong>Important Rules for Multi-Catch Blocks<br>4.2.1. <strong>Rule 1</strong>: Exceptions in Multi-Catch Must Not Have a Parent-Child Relationship<br>4.2.1. <strong>Rule 2: Exception Variable in Multi-Catch is Implicitly </strong><strong><em>final<br>5. </em></strong>Exception Propagation &amp; Rethrowing<br>5.1. Exception Propagation (How Exceptions Travel Up the Call Stack)<br>5.1.1. Fixing Exception Propagation with try-catch<br>5.2 Rethrowing an Exception (Throwing an Exception Again)<br>5.2.1. Case 01: Rethrowing an Exception with a New Exception Type<br>5.2.2. Case 02: Wrap the original exception inside another exception before rethrowing it.<br>5.2.3. Key Differences: Exception Propagation vs. Rethrowing</blockquote><h3>Java 1.7 Enhancements in Exception Handling</h3><p>Java 1.7 introduced <strong>two major enhancements</strong> in exception handling to make code <strong>cleaner, more efficient, and easier to maintain</strong>:</p><blockquote>1. try-with-resources (Automatic Resource Management)<br>2. Multi-Catch Block (Catching Multiple Exceptions in One catch)</blockquote><p><strong>Before Java 1.7 (Manual Resource Handling)</strong></p><p>Before Java 1.7, resources like files, sockets, and database connections had to be closed manually in a finally block, which made the code <strong>verbose and error-prone</strong>.</p><pre>import java.io.*;<br><br>public class WithoutTryWithResources {<br>    public static void main(String[] args) {<br>        BufferedReader br = null;<br>        try {<br>            br = new BufferedReader(new FileReader(&quot;file.txt&quot;));<br>            System.out.println(br.readLine());<br>        } catch (IOException e) {<br>            System.out.println(&quot;Exception: &quot; + e.getMessage());<br>        } finally {<br>            try {<br>                if (br != null) {<br>                    br.close(); // ❌ Manual closing (Prone to errors)<br>                }<br>            } catch (IOException e) {<br>                System.out.println(&quot;Error while closing resource&quot;);<br>            }<br>        }<br>    }<br>}</pre><blockquote><strong>Problems Before Java 1.7:<br></strong>1. Too much boilerplate code (try, catch, and finally) increase length of code and reduces readability.<br>2. Risk of resource leaks if the finally block is not correctly written.</blockquote><h3>try-with-resources</h3><p>With Java 1.7, <strong>resources that implement </strong><strong>AutoCloseable or </strong><strong>Closeable interface</strong> can be declared inside the try block and <strong>automatically closed</strong> when the block exits</p><pre>import java.io.*;<br><br>public class TryWithResourcesExample {<br>    public static void main(String[] args) {<br>        try (BufferedReader br = new BufferedReader(new FileReader(&quot;file.txt&quot;))) { // ✅ No need for finally<br>            System.out.println(br.readLine());<br>        } catch (IOException e) {<br>            System.out.println(&quot;Exception: &quot; + e.getMessage());<br>        }<br>    }<br>}</pre><blockquote><strong>Advantages of </strong><strong>try-with-resources:<br></strong>No need for a finally block to close resources.<br>Automatic resource management (closes resources once try block finishes) either normally or abnormally and hence we are not required to close explicitly.<br>Less error-prone and more readable.</blockquote><h4><strong>Case 01: Declaring Multiple Resources in </strong><strong>try-with-resources</strong></h4><p>1. In Java 1.7 and later, <strong>multiple resources</strong> can be declared in a single try block, separated by <strong>semicolons (</strong><strong>;)</strong>.<br>2. These resources must <strong>implement </strong><strong>AutoCloseable</strong> (or Closeable for IO resources).</p><pre>✅ Example: Multiple Resources in try-with-resources<br><br>import java.io.*;<br><br>public class MultipleResourcesExample {<br>    public static void main(String[] args) {<br>        try (FileReader fr = new FileReader(&quot;file.txt&quot;); <br>             BufferedReader br = new BufferedReader(fr)) { // ✅ Multiple resources<br>            System.out.println(br.readLine());<br>        } catch (IOException e) {<br>            System.out.println(&quot;Exception: &quot; + e.getMessage());<br>        }<br>    }<br>}</pre><blockquote><strong>Key Points:<br></strong>1. FileReader and BufferedReader <strong>both implement </strong><strong>AutoCloseable</strong>, so they can be used inside try-with-resources.<br>2. Resources <strong>must be separated by semicolons (</strong><strong>;)</strong>.<br>3. No need to manually close them in finally—Java <strong>automatically closes them</strong> after execution.</blockquote><blockquote><strong>What is an </strong><strong>AutoCloseable Resource?</strong><br>A resource is AutoCloseable if its class implements java.lang.AutoCloseable.<br>All IO, database, and network-related resources already implement this interface, so programmers do not need to do anything extra.</blockquote><pre>Example: AutoCloseable Interface<br><br>public interface AutoCloseable {<br>    void close() throws Exception; // ✅ Only one method<br>}</pre><blockquote><strong>Key Points:<br>1. </strong>Introduced in <strong>Java 1.7</strong>.<br>2. Contains only <strong>one method</strong> → void close() throws Exception.<br>3. Any class that <strong>implements </strong><strong>AutoCloseable</strong> can be used in try-with-resources.</blockquote><h4>Case 02: All Resource Variables Are Implicitly final</h4><ol><li>Any resource declared in <strong>try-with-resources is implicitly </strong><strong>final</strong>.</li><li><strong>We cannot reassign it</strong> inside the try block. If we try, <strong>Java throws a compile-time error</strong>.</li></ol><pre>Example: Attempting Reassignment (Compile-time Error)<br><br>import java.io.*;<br><br>public class FinalResourceExample {<br>    public static void main(String[] args) {<br>        try (BufferedReader br = new BufferedReader(new FileReader(&quot;file.txt&quot;))) {<br>            br = new BufferedReader(new FileReader(&quot;newfile.txt&quot;)); // ❌ Compile-time error<br>        } catch (IOException e) {<br>            System.out.println(&quot;Exception: &quot; + e.getMessage());<br>        }<br>    }<br></pre><pre>Compile-time Error:<br><br>error: cannot assign a value to final variable &#39;br&#39;</pre><blockquote><strong>Key Points:<br>1. </strong>The <strong>resource variable is </strong><strong>final</strong> inside the try block.<br>2. <strong>Reassignment is not allowed</strong> (br = new BufferedReader(...) causes an error).</blockquote><h4>Case 03: try-with-resources Can Exist Without catch or finally</h4><ol><li><strong>Before Java 1.7</strong>, try <strong>had to be followed by either </strong><strong>catch or </strong><strong>finally</strong>.</li><li><strong>From Java 1.7 onwards</strong>, we can use try-with-resources <strong>without </strong><strong>catch or </strong><strong>finally</strong>, as resources <strong>automatically close</strong>.</li></ol><pre>Example: try-with-resources Without catch or finally<br><br>import java.io.*;<br><br>public class TryWithoutCatchFinally {<br>    public static void main(String[] args) throws IOException { // ✅ No catch or finally<br>        try (BufferedReader br = new BufferedReader(new FileReader(&quot;file.txt&quot;))) {<br>            System.out.println(br.readLine());<br>        }<br>    }<br>}</pre><blockquote><strong>Key Points:<br>1. </strong>No catch or finally needed.<br>2. The resource <strong>closes automatically</strong>.<br>3. If an exception occurs, it <strong>propagates to the caller</strong>.</blockquote><blockquote>The main advantage of try with resources is we are not required to write finally block explicitly because we are not required to close, resources excplicitly.</blockquote><h3>Multi-Catch Block</h3><ol><li>Java 1.7 introduced <strong>multi-catch blocks</strong>, allowing a single catch block to handle <strong>multiple exceptions</strong> using the <strong>pipe (</strong><strong>|) operator</strong>.</li><li>Before Java 1.7, we had to write <strong>separate </strong><strong>catch blocks</strong> for each exception, even if they had the same handling logic.</li></ol><p><strong>Before Java 1.7 (Multiple </strong><strong>catch Blocks Required)</strong></p><p>If multiple exceptions were possible, we needed <strong>separate </strong><strong>catch blocks</strong>, even if they contained <strong>duplicate code</strong>.</p><pre>public class MultiCatchBeforeJava7 {<br>    public static void main(String[] args) {<br>        try {<br>            int arr[] = new int[5];<br>            arr[10] = 30 / 0; // May throw both ArithmeticException &amp; ArrayIndexOutOfBoundsException<br>        } catch (ArithmeticException e) {<br>            System.out.println(&quot;Arithmetic Exception occurred&quot;);<br>        } catch (ArrayIndexOutOfBoundsException e) {<br>            System.out.println(&quot;Array Index Out Of Bounds Exception occurred&quot;);<br>        }<br>    }<br>}</pre><pre>Output (If division occurs first):<br><br>Arithmetic Exception occurred</pre><pre>Output (If index out of bounds occurs first):<br><br>Array Index Out Of Bounds Exception occurred</pre><blockquote><strong>Problems Before Java 1.7:</strong><br>1. Duplicate code in each catch block.<br>2. More lines of code, making maintenance difficult.</blockquote><p>With Java 1.7, we can <strong>combine multiple exceptions into a single </strong><strong>catch block</strong> using | (pipe operator).</p><pre>public class MultiCatchExample {<br>    public static void main(String[] args) {<br>        try {<br>            int arr[] = new int[5];<br>            arr[10] = 30 / 0; // May throw both ArithmeticException &amp; ArrayIndexOutOfBoundsException<br>        } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) { // ✅ One catch block<br>            System.out.println(&quot;Exception occurred: &quot; + e);<br>        }<br>    }<br>}</pre><pre>Output (If division occurs first)<br><br>Exception occurred: java.lang.ArithmeticException: / by zero</pre><pre>Output (If index out of bounds occurs first):<br><br>Exception occurred: java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 5</pre><blockquote><strong>Advantages of Multi-Catch Block:<br></strong>1. Reduces duplicate code (same handling logic in one place).<br>2. Improves readability and maintainability.<br>3. Simplifies exception handling when multiple exceptions need similar handling.</blockquote><h4>Important Rules for Multi-Catch Blocks</h4><blockquote><strong>Rule 1</strong>: Exceptions in Multi-Catch Must Not Have a Parent-Child Relationship</blockquote><pre>Invalid Example (Compile-time error):<br><br>try {<br>    int result = 10 / 0;<br>} catch (ArithmeticException | Exception e) { // ❌ Parent-Child Relationship<br>    System.out.println(&quot;Exception occurred: &quot; + e);<br>}</pre><pre>Error Message:<br><br>error: Alternatives in a multi-catch statement cannot be related by subclassing</pre><p><strong>Fix:</strong> Catch the child exception first or use separate catch blocks.</p><blockquote><strong>Rule 2: Exception Variable in Multi-Catch is Implicitly </strong><strong>final</strong></blockquote><ul><li>The exception variable (e) in a multi-catch block <strong>cannot be reassigned</strong>.</li></ul><pre>Invalid Example (Compile-time error):<br><br>try {<br>    int arr[] = new int[5];<br>    arr[10] = 30 / 0;<br>} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {<br>    e = new Exception(&quot;New Exception&quot;); // ❌ Compile-time error<br>}</pre><pre>✅ Error Message<br><br>error: The exception parameter e is implicitly declared final</pre><h3>Exception Propagation &amp; Rethrowing</h3><p>Java provides mechanisms for <strong>exception propagation</strong> and <strong>rethrowing exceptions</strong> to improve error handling and debugging.</p><h4>Exception Propagation (How Exceptions Travel Up the Call Stack)</h4><p><strong>Definition:</strong> Exception propagation is the process where <strong>an exception moves up the call stack</strong> if it is <strong>not handled in the current method</strong>.</p><blockquote><strong>How It Works:</strong><br>1. If a method does not handle an exception, it passes it to the caller method.<br>2. This continues until it is either handled or the program crashes if it reaches the JVM.</blockquote><pre>✅ Example: Exception Propagation<br><br>public class ExceptionPropagationExample {<br>    static void method3() {<br>        int result = 10 / 0; // ❌ ArithmeticException occurs here<br>    }<br><br>  static void method2() {<br>        method3(); // Exception propagates here<br>    }<br>    static void method1() {<br>        method2(); // Exception propagates here<br>    }<br>    public static void main(String[] args) {<br>        method1(); // ❌ JVM terminates the program<br>    }<br>}</pre><pre>Output (Uncaught Exception):<br><br>Exception in thread &quot;main&quot; java.lang.ArithmeticException: / by zero<br>    at ExceptionPropagationExample.method3<br>    at ExceptionPropagationExample.method2<br>    at ExceptionPropagationExample.method1<br>    at ExceptionPropagationExample.main</pre><blockquote><strong>Key Takeaways from Exception Propagation</strong>:<br>1. Unchecked exceptions (RuntimeException) propagate automatically up the call stack.<br>2. Checked exceptions (Exception) must be explicitly declared using throws.<br>3. If an exception remains unhandled, it reaches the JVM and terminates the program.</blockquote><h4><strong>Fixing Exception Propagation with </strong><strong><em>try-catch</em></strong></h4><p>To <strong>stop propagation</strong>, we must <strong>handle the exception at any level</strong> in the call stack.</p><pre>public class ExceptionHandledPropagation {<br>    static void method3() {<br>        int result = 10 / 0; // ❌ ArithmeticException occurs<br>    }<br><br>  static void method2() {<br>        try {<br>            method3(); // ✅ Exception handled here<br>        } catch (ArithmeticException e) {<br>            System.out.println(&quot;Exception handled in method2: &quot; + e.getMessage());<br>        }<br>    }<br>    public static void main(String[] args) {<br>        method2(); // ✅ Program continues normally<br>        System.out.println(&quot;Program execution continues...&quot;);<br>    }<br>}</pre><pre>Output:<br><br>Exception handled in method2: / by zero<br>Program execution continues...</pre><blockquote><strong>Key Takeaway:<br></strong>Handling the exception in <strong>method2() stops propagation</strong>, preventing the JVM from terminating the program.</blockquote><h4>Rethrowing an Exception (Throwing an Exception Again)</h4><h4>Case 01: Rethrowing an Exception with a New Exception Type</h4><p><strong>Definition:</strong> Rethrowing means <strong>catching an exception and then throwing it again</strong> so that it propagates further.</p><blockquote><strong>Use Cases:<br>1. </strong>When we <strong>want to log or modify an exception message</strong> before passing it to another method.<br>2. When we want to <strong>convert a checked exception into an unchecked exception</strong>.</blockquote><pre>✅ Example: Rethrowing an Exception<br><br>public class RethrowingExceptionExample {<br>    static void method3() throws ArithmeticException {<br>        throw new ArithmeticException(&quot;Original Exception&quot;); // ❌ Throws exception<br>    }<br><br>    static void method2() throws ArithmeticException {<br>        try {<br>            method3();<br>        } catch (ArithmeticException e) {<br>            System.out.println(&quot;Logging Exception in method2: &quot; + e.getMessage());<br>            throw e; // ✅ Rethrowing exception<br>        }<br>    }<br>    public static void main(String[] args) {<br>        try {<br>            method2();<br>        } catch (ArithmeticException e) {<br>            System.out.println(&quot;Exception handled in main: &quot; + e.getMessage());<br>        }<br>    }<br>}</pre><pre>Output:<br><br>Logging Exception in method2: Original Exception<br>Exception handled in main: Original Exception</pre><blockquote><strong>Key Takeaways from Rethrowing an Exception:</strong><br>1. The exception is first caught in method2() but thrown again using throw e.<br>2. Main method handles it after logging in method2().<br>3. This allows both logging and proper exception handling.</blockquote><h4>Case 02: W<strong>rap the original exception inside another exception</strong> before rethrowing it.</h4><p>Sometimes, we need to <strong>wrap the original exception inside another exception</strong> before rethrowing it.</p><pre>Example: Wrapping and Rethrowing as a Custom Exception:<br><br>class CustomException extends Exception {<br>    public CustomException(String message, Throwable cause) {<br>        super(message, cause);<br>    }<br>}<br><br>public class RethrowWithCustomException {<br>    static void method3() throws ArithmeticException {<br>        throw new ArithmeticException(&quot;Division by zero&quot;);<br>    }<br>    static void method2() throws CustomException {<br>        try {<br>            method3();<br>        } catch (ArithmeticException e) {<br>            throw new CustomException(&quot;Wrapped Exception in method2&quot;, e); // ✅ Wrapping original exception<br>        }<br>    }<br>    public static void main(String[] args) {<br>        try {<br>            method2();<br>        } catch (CustomException e) {<br>            System.out.println(&quot;Exception handled in main: &quot; + e.getMessage());<br>            System.out.println(&quot;Original Cause: &quot; + e.getCause());<br>        }<br>    }<br>}</pre><pre>Output:<br><br>Exception handled in main: Wrapped Exception in method2<br>Original Cause: java.lang.ArithmeticException: Division by zero</pre><blockquote><strong>Key Takeaways:</strong><br>1. We wrap the original ArithmeticException inside CustomException before throwing it again.<br>2. e.getCause() gives the original exception for debugging.<br>Useful for converting checked exceptions into meaningful runtime exceptions.</blockquote><h4>Key Differences: Exception Propagation vs. Rethrowing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*e5dIdR_5GVmeHKiAE0ierg.png" /></figure><h4>Conclusion:</h4><p>Understanding <strong>exception propagation</strong> and <strong>rethrown exceptions</strong> allows developers to <strong>manage errors effectively</strong> without unnecessary code duplication.</p><p>✔ <strong>Unchecked exceptions</strong> propagate automatically if unhandled.<br> ✔ <strong>Checked exceptions</strong> must be explicitly declared (throws) or handled.<br> ✔ <strong>Rethrowing exceptions</strong> enables better <strong>logging, debugging, and custom exception handling</strong>.</p><p>This concludes our exceptional handling series.</p><p>Previous Article: <a href="https://medium.com/@adityaharendramall/core-java-exceptional-handling-08-customized-exception-common-exceptions-7a500ea9e0d9">https://medium.com/@adityaharendramall/core-java-exceptional-handling-08-customized-exception-common-exceptions-7a500ea9e0d9</a></p><p>Playlist: <a href="https://medium.com/@adityaharendramall/list/core-java-exception-handling-79bf587eb712">https://medium.com/@adityaharendramall/list/core-java-exception-handling-79bf587eb712</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1e396b41c0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Core Java — Exceptional Handling — 08 — Customized exception, common exceptions]]></title>
            <link>https://medium.com/@adityaharendramall/core-java-exceptional-handling-08-customized-exception-common-exceptions-7a500ea9e0d9?source=rss-826dae311f2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a500ea9e0d9</guid>
            <category><![CDATA[core-java]]></category>
            <category><![CDATA[exception-handling]]></category>
            <dc:creator><![CDATA[Aditya Harendra Mall]]></dc:creator>
            <pubDate>Wed, 19 Mar 2025 17:16:57 GMT</pubDate>
            <atom:updated>2025-06-02T10:24:13.151Z</atom:updated>
            <content:encoded><![CDATA[<h3>Core Java — Exceptional Handling — 08 — Customized exception, common exceptions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nwMCZKWeJl7EBRB4_lhrZQ.png" /></figure><blockquote><strong>Topics covered in this article</strong><br>1. Exception handling keywords and each example<br>2. Various Possible Compile-Time Errors in Exception Handling<em>.<br>3. </em>Examples of Customized Exception (User-Defined Exception) in Java<em><br>3.1. </em><strong>Example 1</strong>: Custom Checked Exception<em><br>3.2. </em><strong>Example 2</strong>: Custom Unchecked Exception<br>4. Comprehensive Guide to 14 Common Java Exceptions<br>4.1. <strong>Programmatic Exceptions</strong> (Thrown explicitly by the programmer using <em>throw) <br>4.2. </em><strong>JVM Exceptions</strong> (Raised automatically by the JVM)</blockquote><h3><strong>Exception Handling Keywords</strong></h3><p>Java provides <strong>five</strong> key exception-handling keywords to manage runtime errors effectively:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*sgInyuZPljc1ul2KmVboiA.png" /></figure><p><strong><em>Quick Examples for Each Keyword</em></strong></p><p>1️⃣ try-catch Example</p><pre>try {<br>    int result = 10 / 0; // ❌ Will cause ArithmeticException<br>} catch (ArithmeticException e) {<br>    System.out.println(&quot;Cannot divide by zero!&quot;);<br>}</pre><p>2️⃣ finally Block Example</p><pre>try {<br>    System.out.println(&quot;Inside try block&quot;);<br>} finally {<br>    System.out.println(&quot;Finally block always executes!&quot;);<br>}</pre><p>3️⃣ throw Example</p><pre>throw new IllegalArgumentException(&quot;Invalid input!&quot;); // ❌ Throws an exception manually</pre><p>4️⃣ throws Example</p><pre>void readFile() throws IOException {<br>    FileReader file = new FileReader(&quot;data.txt&quot;); // Might cause IOException<br>}</pre><h3><strong>Various Possible Compile-Time Errors in Exception Handling</strong></h3><p>1️⃣ unreported exception XXX; must be caught or declared to be thrown</p><blockquote>Cause:<br>A <strong>checked exception</strong> is thrown inside a method, but it is <strong>neither handled using </strong><strong>try-catch</strong> nor <strong>declared using </strong><strong>throws</strong>.</blockquote><pre>Example: Compile-time Error<br><br>import java.io.FileReader;<br><br>public class UnreportedExceptionExample {<br>    public static void main(String[] args) {<br>        FileReader file = new FileReader(&quot;data.txt&quot;); // ❌ Compile-time error<br>    }<br>}</pre><pre>🚨 Error:<br><br>error: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown</pre><p><strong>Solution 1</strong>: Handle using try-catch</p><pre>try {<br>    FileReader file = new FileReader(&quot;data.txt&quot;);<br>} catch (FileNotFoundException e) {<br>    System.out.println(&quot;Exception caught: &quot; + e.getMessage());<br>}</pre><p><strong>Solution 2</strong>: Declare using throws</p><pre>static void readFile() throws FileNotFoundException {<br>    FileReader file = new FileReader(&quot;data.txt&quot;);<br>}</pre><p>2️⃣ exception XXX has already been caught</p><blockquote>Cause:<br>A <strong>child exception is caught after its parent exception</strong>, making the second catch block <strong>unreachable</strong>.</blockquote><pre>❌ Example: Compile-time Error<br><br>public class DuplicateCatchBlock {<br>    public static void main(String[] args) {<br>        try {<br>            throw new NullPointerException();<br>        } catch (Exception e) { // ❌ Catches all exceptions<br>            System.out.println(&quot;Caught Exception&quot;);<br>        } catch (NullPointerException e) { // ❌ Compile-time error (Unreachable)<br>            System.out.println(&quot;Caught NullPointerException&quot;);<br>        }<br>    }<br>}</pre><pre>🚨 Error:<br><br>error: exception NullPointerException has already been caught</pre><p><strong>Solution</strong>: Catch specific exceptions first</p><pre>try {<br>    throw new NullPointerException();<br>} catch (NullPointerException e) {  // ✅ Specific exception first<br>    System.out.println(&quot;Caught NullPointerException&quot;);<br>} catch (Exception e) {  // ✅ General exception later<br>    System.out.println(&quot;Caught Exception&quot;);<br>}</pre><p>3️⃣ exception XXX is never thrown in body of corresponding try statement</p><blockquote>Cause:<br>The catch block is defined for an exception <strong>that never occurs</strong> in the try block.</blockquote><pre>❌ Example: Compile-time Error<br><br>public class UnnecessaryCatch {<br>    public static void main(String[] args) {<br>        try {<br>            System.out.println(&quot;No exception occurs here.&quot;);<br>        } catch (IOException e) { // ❌ Compile-time error<br>            System.out.println(&quot;This will never execute.&quot;);<br>        }<br>    }<br>}</pre><pre>🚨 Error:<br> <br>error: exception java.io.IOException is never thrown in body of corresponding try statement</pre><p><strong>Solution</strong>: Remove unnecessary catch block</p><pre>try {<br>    System.out.println(&quot;No exception here.&quot;); <br>} catch (Exception e) {  // ✅ Catch only exceptions that may occur<br>    System.out.println(&quot;This will execute if an exception occurs.&quot;);<br>}</pre><p>4️⃣ unreachable statement</p><blockquote>Cause:<br>A <strong>statement after </strong><strong>throw or </strong><strong>return</strong> is unreachable.</blockquote><pre>❌ Example: Compile-time Error<br><br>public class UnreachableCode {<br>    public static void main(String[] args) {<br>        throw new RuntimeException(&quot;Error occurred&quot;);<br>        System.out.println(&quot;This will never execute!&quot;); // ❌ Compile-time error<br>    }<br>}</pre><pre>🚨 Error:<br><br>error: unreachable statement</pre><p><strong>Solution</strong>: Remove unreachable code</p><pre>public class ReachableCode {<br>    public static void main(String[] args) {<br>        System.out.println(&quot;This will execute before the exception.&quot;);<br>        throw new RuntimeException(&quot;Error occurred&quot;);<br>    }<br>}</pre><p>5️⃣incompatible types: found: Test required: java.lang.Throwable</p><blockquote>Cause:<br>1. The throw statement <strong>must throw an instance of </strong><strong>Throwable</strong> (i.e., Exception or Error).<br>2. If a <strong>non-Throwable object</strong> (like String) is thrown, Java throws a <strong>compile-time error</strong>.</blockquote><pre>❌ Example: Compile-time Error<br><br>public class InvalidThrow {<br>    public static void main(String[] args) {<br>        throw &quot;This is an exception&quot;; // ❌ Compile-time error<br>    }<br>}</pre><pre>🚨 Error:<br><br>error: incompatible types: String cannot be converted to Throwable</pre><p><strong>Solution</strong>: Use a valid exception</p><pre>throw new IllegalArgumentException(&quot;Invalid input!&quot;); // ✅ Correct</pre><p>6️⃣ try without catch or finally</p><blockquote>Cause:<br>A try block <strong>must be followed</strong> by <strong>either a </strong><strong>catch block</strong> or a <strong>finally block</strong>.</blockquote><pre>❌ Example: Compile-time Error<br><br>public class TryWithoutCatchOrFinally {<br>    public static void main(String[] args) {<br>        try {  // ❌ Compile-time error<br>            System.out.println(&quot;Inside try block&quot;);<br>        }  <br>    }<br>}</pre><pre>🚨 Error:<br><br>error: &#39;try&#39; without &#39;catch&#39;, &#39;finally&#39; or resource declaration</pre><p><strong>Solution</strong>: Add catch or finally</p><pre>try {<br>    System.out.println(&quot;Inside try block&quot;);<br>} finally {  // ✅ Must be followed by `catch` or `finally`<br>    System.out.println(&quot;Finally block always executes&quot;);<br>}</pre><p>7️⃣ catch without try</p><blockquote>Cause:<br>A catch block <strong>must always be associated</strong> with a try block.</blockquote><pre>❌ Example: Compile-time Error<br><br>public class CatchWithoutTry {<br>    public static void main(String[] args) {<br>        catch (Exception e) { // ❌ Compile-time error<br>            System.out.println(&quot;Exception caught.&quot;);<br>        }<br>    }<br>}</pre><pre>🚨 Error:<br><br>error: &#39;catch&#39; without &#39;try&#39;</pre><p><strong>Solution</strong>: Use a try block before catch</p><pre>try {<br>    int a = 10 / 0;<br>} catch (ArithmeticException e) { // ✅ Correct usage<br>    System.out.println(&quot;Caught Exception: &quot; + e.getMessage());<br>}</pre><p>8️⃣ finally without try</p><blockquote>Cause:<br>A finally block <strong>must always be associated</strong> with a try block.</blockquote><pre>Example: Compile-time Error<br><br>public class FinallyWithoutTry {<br>    public static void main(String[] args) {<br>        finally { // ❌ Compile-time error<br>            System.out.println(&quot;Finally block&quot;);<br>        }<br>    }<br>}</pre><pre>Error:<br><br>error: &#39;finally&#39; without &#39;try&#39;</pre><p><strong>Solution</strong>: Use a try block before finally</p><pre>try {<br>    System.out.println(&quot;Inside try block&quot;);<br>} finally { // ✅ Correct usage<br>    System.out.println(&quot;Finally block always executes&quot;);<br>}</pre><h3>Examples of Customized Exception (User-Defined Exception) in Java</h3><p>In Java, we can create our own <strong>custom exceptions</strong> by <strong>extending </strong><strong>Exception (checked exception) or </strong><strong>RuntimeException (unchecked exception)</strong>. This helps in defining meaningful exception messages and handling specific business logic errors.</p><p><strong>Example 1</strong>: Custom Checked Exception</p><p>A checked exception <strong>must be declared using </strong><strong>throws</strong> and <strong>handled using </strong><strong>try-catch</strong>.</p><pre>// Custom checked exception class (Extending Exception)<br>class AgeRestrictionException extends Exception {<br>    public AgeRestrictionException(String message) {<br>        super(message);<br>    }<br>}<br><br>public class CustomCheckedException {<br>    static void checkAge(int age) throws AgeRestrictionException {<br>        if (age &lt; 18) {<br>            throw new AgeRestrictionException(&quot;Access denied - You must be 18 or older.&quot;);<br>        }<br>        System.out.println(&quot;Access granted - You are eligible!&quot;);<br>    }<br>    public static void main(String[] args) {<br>        try {<br>            checkAge(16); // ❌ Will throw AgeRestrictionException<br>        } catch (AgeRestrictionException e) {<br>            System.out.println(&quot;Exception caught: &quot; + e.getMessage());<br>        }<br>    }<br>}</pre><pre>Output:<br><br>Exception caught: Access denied - You must be 18 or older.</pre><blockquote><strong>Why Use a Checked Exception?<br></strong>1. It forces the caller to handle or declare the exception (throws).<br>2. Suitable for business rules validation (e.g., age restrictions, file access).</blockquote><p><strong>Example 2</strong>: Custom Unchecked Exception</p><p>An unchecked exception <strong>does not need </strong><strong>throws or </strong><strong>try-catch</strong>, but can still be caught if needed.</p><pre>// Custom unchecked exception class (Extending RuntimeException)<br>class InvalidSalaryException extends RuntimeException {<br>    public InvalidSalaryException(String message) {<br>        super(message);<br>    }<br>}<br><br>public class CustomUncheckedException {<br>    static void setSalary(int salary) {<br>        if (salary &lt; 0) {<br>            throw new InvalidSalaryException(&quot;Salary cannot be negative!&quot;);<br>        }<br>        System.out.println(&quot;Salary set to: &quot; + salary);<br>    }<br>    public static void main(String[] args) {<br>        try {<br>            setSalary(-5000); // ❌ Will throw InvalidSalaryException<br>        } catch (InvalidSalaryException e) {<br>            System.out.println(&quot;Exception caught: &quot; + e.getMessage());<br>        }<br>    }<br>}</pre><pre>Output:<br><br>Exception caught: Salary cannot be negative!</pre><blockquote><strong>Why Use an Unchecked Exception?<br></strong>1. No need to explicitly handle it using try-catch.<br>2. Suitable for programming errors (e.g., invalid input, null values).</blockquote><blockquote><strong>Note:</strong><br>1. The throw keyword is <strong>best suited for user-defined (customized) exceptions</strong>, rather than predefined exceptions.<br>2. It is <strong>highly recommended</strong> to define customized exceptions as <strong>unchecked exceptions</strong> by extending RuntimeException, rather than non-exception classes.<br>3. The <strong>super(s)</strong> statement is used to <strong>pass the exception message</strong> to the <strong>parent class (</strong><strong>Exception or </strong><strong>RuntimeException)</strong>, making it available for the <strong>default exception handler</strong> to display.</blockquote><pre>The exception class hierarchy follows this structure:<br><br>TooYoungException { super(s) }  →  Exception { super(s) }  →  Throwable { printStackTrace() }</pre><h3>Comprehensive Guide to 14 Common Java Exceptions</h3><blockquote>Exceptions in Java can be broadly categorized into:<br>1. <strong>JVM Exceptions</strong> (Raised automatically by the JVM)<br>2. <strong>Programmatic Exceptions</strong> (Thrown explicitly by the programmer using throw)</blockquote><h4>JVM Exceptions (Raised Automatically by JVM)</h4><p>1. ArithmeticException</p><blockquote><strong>Parent Class:</strong> RuntimeException (Unchecked Exception)<br><strong>When It Occurs:</strong> This exception occurs when an invalid mathematical operation is performed, such as division by zero.</blockquote><pre>Example:<br><br>public class ArithmeticExceptionExample {<br>    public static void main(String[] args) {<br>        int result = 10 / 0; // ❌ ArithmeticException: / by zero<br>    }<br>}</pre><pre>Output:<br><br>Exception in thread &quot;main&quot; java.lang.ArithmeticException: / by zero</pre><p>2. NullPointerException</p><blockquote><strong>Parent Class:</strong> RuntimeException (Unchecked Exception)<br><strong>When It Occurs:</strong> This exception occurs when an operation is performed on an object reference that is null.</blockquote><pre>Example:<br><br>public class NullPointerExceptionExample {<br>    public static void main(String[] args) {<br>        String s = null;<br>        System.out.println(s.length()); // ❌ NullPointerException<br>    }<br>}</pre><pre>Output:<br><br>Exception in thread &quot;main&quot; java.lang.NullPointerException</pre><p>3. ArrayIndexOutOfBoundsException</p><blockquote><strong>Parent Class:</strong> RuntimeException (Unchecked Exception)<br><strong>When It Occurs:</strong> This exception occurs when accessing an invalid index in an array.</blockquote><pre>Example:<br><br>public class ArrayIndexOutOfBoundsExample {<br>    public static void main(String[] args) {<br>        int[] arr = new int[5];<br>        System.out.println(arr[10]); // ❌ ArrayIndexOutOfBoundsException<br>    }<br>}</pre><pre>Output:<br><br>Exception in thread &quot;main&quot; java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length </pre><p>4. ClassCastException</p><p><strong>Parent Class:</strong> RuntimeException (Unchecked Exception)<br><strong>When It Occurs:</strong> This exception occurs when an object is cast to an incompatible type.</p><pre>Example:<br><br>public class ClassCastExceptionExample {<br>    public static void main(String[] args) {<br>        Object obj = new String(&quot;Java&quot;);<br>        Integer num = (Integer) obj; // ❌ ClassCastException<br>    }<br>}</pre><pre>Output:<br><br>Exception in thread &quot;main&quot; java.lang.ClassCastException</pre><p>5. StackOverflowError</p><blockquote><strong>Parent Class:</strong> Error<br><strong>When It Occurs:</strong> This error occurs when a method keeps calling itself recursively without a base condition.</blockquote><pre>Example:<br><br>public class StackOverflowExample {<br>    public static void recursiveMethod() {<br>        recursiveMethod(); // ❌ StackOverflowError<br>    }<br>    public static void main(String[] args) {<br>        recursiveMethod();<br>    }<br></pre><pre>Output:<br><br>Exception in thread &quot;main&quot; java.lang.StackOverflowError</pre><p>6. NoClassDefFoundError</p><blockquote><strong>Parent Class:</strong> Error<br><strong>When It Occurs:</strong> This error occurs when a required .class file is missing at runtime.</blockquote><ul><li>If you compile MyClass.java but delete MyClass.class before running it, you&#39;ll get:</li></ul><pre>Example:<br><br>Exception in thread &quot;main&quot; java.lang.NoClassDefFoundError: MyClass</pre><p>7. IllegalThreadStateException</p><blockquote><strong>Parent Class:</strong> RuntimeException<br><strong>When It Occurs:</strong> This exception occurs when an operation is performed on a thread in an inappropriate state, such as starting a thread twice.</blockquote><pre>Example:<br><br>public class IllegalThreadStateExceptionExample extends Thread {<br>    public void run() {<br>        System.out.println(&quot;Thread is running...&quot;);<br>    }<br>    public static void main(String[] args) {<br>        IllegalThreadStateExceptionExample t = new IllegalThreadStateExceptionExample();<br>        t.start();<br>        t.start(); // ❌ IllegalThreadStateException<br>    }<br>}</pre><pre>Output:<br><br>Exception in thread &quot;main&quot; java.lang.IllegalThreadStateException</pre><p>8. ExceptionInInitializerError</p><blockquote><strong>Parent Class:</strong> Error<br><strong>When It Occurs:</strong> This occurs when an exception occurs in a static initializer block.</blockquote><pre>Example:<br><br>public class ExceptionInInitializerExample {<br>    static {<br>        int a = 10 / 0; // ❌ ExceptionInInitializerError<br>    }<br>}</pre><pre>Output:<br><br>Exception in thread &quot;main&quot; java.lang.ExceptionInInitializerError</pre><p>9. AssertionError</p><blockquote><strong>Parent Class:</strong> Error<br><strong>When It Occurs:</strong> This error occurs when an assertion (assert) fails.</blockquote><pre>Example:<br><br>public class AssertionErrorExample {<br>    public static void main(String[] args) {<br>        int x = 10;<br>        assert x == 5 : &quot;Assertion failed!&quot;; // ❌ AssertionError<br>    }<br>}</pre><pre>Output:<br><br>Exception in thread &quot;main&quot; java.lang.AssertionError: Assertion failed!</pre><h4>Programmatic Exceptions (Raised by the Programmer using throw)</h4><p>10. IllegalArgumentException</p><blockquote><strong>Parent Class:</strong> RuntimeException<br><strong>When It Occurs:</strong> This exception occurs when an invalid argument is passed to a method.</blockquote><pre>Example:<br><br>public class IllegalArgumentExceptionExample {<br>    public static void setAge(int age) {<br>        if (age &lt; 0) {<br>            throw new IllegalArgumentException(&quot;Age cannot be negative&quot;);<br>        }<br>    }<br><br>public static void main(String[] args) {<br>        setAge(-5); // ❌ IllegalArgumentException<br>    }<br>}</pre><p>11. NumberFormatException</p><blockquote><strong>Parent Class:</strong> IllegalArgumentException<br><strong>When It Occurs:</strong> This exception occurs when converting an invalid String to a number.</blockquote><pre>int num = Integer.parseInt(&quot;ABC&quot;); // ❌ NumberFormatException</pre><p>12. IOException</p><blockquote><strong>Parent Class:</strong> Exception (Checked Exception)<br><strong>When It Occurs:</strong> This exception occurs when an I/O operation fails.</blockquote><pre>Example:<br><br>import java.io.FileReader;<br>FileReader file = new FileReader(&quot;nonexistent.txt&quot;); // ❌ IOException</pre><p>13. SQLException</p><blockquote><strong>Parent Class:</strong> Exception (Checked Exception)<br><strong>When It Occurs:</strong> This exception occurs when an SQL query fails.</blockquote><p>14. CustomException (User-defined Exception)</p><p>P<strong>arent Class:</strong> Exception (Checked) or RuntimeException (Unchecked)</p><pre>Example:<br><br>class InvalidAgeException extends RuntimeException {<br>    public InvalidAgeException(String message) {<br>        super(message);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*P1_X2qfNUJjDuLTgKuXNIQ.png" /></figure><blockquote><strong><em>What’s next?</em></strong><em><br>1. </em>Java 1.7 Enhancements in Exception Handling<br>2. <strong>Before Java 1.7 (Manual Resource Handling)<br>3. </strong><strong><em>try-with-resources</em> (Automatic Resource Management)<br>3.1. </strong>Case 01: Declaring Multiple Resources in <em>try-with-resources<br>3.1.1. </em><strong>What is an </strong><strong><em>AutoCloseable</em> Resource?<br>3.2. </strong>Case 02: All Resource Variables Are Implicitly <em>final<br>3.3.</em>Case 03: <em>try-with-resources</em> Can Exist Without <em>catch</em> or <em>finally<br>4. </em>Multi-Catch Block<br>4.1. <strong>Before Java 1.7 (Multiple </strong><strong><em>catch</em> Blocks Required)<br>4.2. </strong>Important Rules for Multi-Catch Blocks<br>4.2.1. <strong>Rule 1</strong>: Exceptions in Multi-Catch Must Not Have a Parent-Child Relationship<br>4.2.1. <strong>Rule 2: Exception Variable in Multi-Catch is Implicitly </strong><strong><em>final<br>5. </em></strong>Exception Propagation &amp; Rethrowing<br>5.1. Exception Propagation (How Exceptions Travel Up the Call Stack)<br>5.1.1. Fixing Exception Propagation with <em>try-catch<br>5.2 </em>Rethrowing an Exception (Throwing an Exception Again)<br>5.2.1. Case 01: Rethrowing an Exception with a New Exception Type<br>5.2.2. Case 02: Wrap the original exception inside another exception before rethrowing it.<br>5.2.3. Key Differences: Exception Propagation vs. Rethrowing</blockquote><p>Previous Article : — <a href="https://medium.com/@adityaharendramall/core-java-exceptional-handling-07-throws-and-its-cases-bbac4364b5f4">https://medium.com/@adityaharendramall/core-java-exceptional-handling-07-throws-and-its-cases-bbac4364b5f4</a></p><p>Next Article : — <a href="https://medium.com/@adityaharendramall/core-java-exceptional-handling-09-try-with-resources-multi-catch-block-c1e396b41c0f">https://medium.com/@adityaharendramall/core-java-exceptional-handling-09-try-with-resources-multi-catch-block-c1e396b41c0f</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a500ea9e0d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Core Java — Exceptional Handling — 07— Throws and it’s Cases]]></title>
            <link>https://medium.com/@adityaharendramall/core-java-exceptional-handling-07-throws-and-its-cases-bbac4364b5f4?source=rss-826dae311f2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbac4364b5f4</guid>
            <category><![CDATA[core-java]]></category>
            <category><![CDATA[exception-handling]]></category>
            <dc:creator><![CDATA[Aditya Harendra Mall]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 17:36:47 GMT</pubDate>
            <atom:updated>2025-05-09T06:19:50.898Z</atom:updated>
            <content:encoded><![CDATA[<h3>Core Java — Exceptional Handling — 07— Throws and it’s Cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4WZyS7MVLaAus57WYWY22w.png" /></figure><blockquote><strong>Topics covered in this article</strong><br>1. Throws<br>2. <em>Case 01: </em>Either handle it using a try-catch block or declare it using the throws keyword.<em><br>3. Case 02: </em>The throws keyword used only in method and constructor signatures<em><br>4. Case 03: </em><em>throws Can Only Be Used with </em><em>Throwable Types in Java<br>5. Case 04: </em>No possibility of a checked exception occurring</blockquote><h3>Throws keyword</h3><ol><li>In Java, the throws keyword is used in a <strong>method signature</strong> to declare that the method may throw one or more exceptions. It informs the <strong>caller of the method</strong> that an exception might occur and needs to be handled.</li><li>In our program, if there is a possibility of a <strong>checked exception</strong> being raised, we must <strong>either handle it using a </strong><strong>try-catch block</strong> or <strong>declare it using the </strong><strong>throws keyword</strong>. Otherwise, we will get a <strong>compile-time error</strong> saying:</li></ol><pre>🚨 &quot;Unreported exception XXX; must be caught or declared to be thrown.&quot;</pre><h4><strong>Case 01</strong>: E<strong>ither handle it using a </strong><strong>try-catch block</strong> or <strong>declare it using the </strong><strong>throws keyword</strong>.</h4><p>In our program, if there is a possibility of a <strong>checked exception</strong> occurring, we must <strong>either handle it using a </strong><strong>try-catch block</strong> or <strong>declare it using the </strong><strong>throws keyword</strong>. Otherwise, we will get a <strong>compile-time error</strong> stating:</p><p><strong>Example</strong>: Compile-time Error Due to Unhandled Checked Exception</p><pre>import java.io.FileReader;<br><br>public class CheckedExceptionExample {<br>    public static void main(String[] args) {<br>        FileReader file = new FileReader(&quot;data.txt&quot;); // ❌ Compile-time error<br>    }<br>}</pre><pre>Compile-time Error:<br> <br>error: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown<br>        FileReader file = new FileReader(&quot;data.txt&quot;)</pre><p>FileReader might throw a FileNotFoundException, which is a <strong>checked exception</strong>.</p><blockquote><strong>Solution 1</strong>: Handle Using try-catch</blockquote><pre>import java.io.FileReader;<br>import java.io.IOException;<br><br>public class HandleCheckedException {<br>    public static void main(String[] args) {<br>        try {<br>            FileReader file = new FileReader(&quot;data.txt&quot;);<br>            System.out.println(&quot;File opened successfully!&quot;);<br>        } catch (IOException e) {  // ✅ Handling the exception<br>            System.out.println(&quot;Exception caught: &quot; + e.getMessage());<br>        }<br>    }<br>}</pre><pre>Output (If file is missing):<br><br>  Exception caught: data.txt (No such file or directory)</pre><blockquote><strong>Solution 2</strong>: Declare Using throws</blockquote><pre>import java.io.FileReader;<br>import java.io.IOException;<br><br>public class ThrowsExample {<br>    static void readFile() throws IOException { // Delegating exception to the caller<br>        FileReader file = new FileReader(&quot;data.txt&quot;);<br>    }<br>    public static void main(String[] args) {<br>        try {<br>            readFile(); // Caller method must handle the exception<br>        } catch (IOException e) {<br>            System.out.println(&quot;Exception handled in main: &quot; + e.getMessage());<br>        }<br>    }<br>}</pre><pre>Output (If file is missing):<br><br>Exception handled in main: data.txt (No such file or directory)</pre><p>Here, readFile() does not handle the exception itself but instead delegates it to main() using throws.</p><blockquote><strong>Key Takeaways<br></strong> 1. <strong><em>throws</em></strong> delegates exception handling to another method or the JVM. It is <strong>required only for checked exceptions</strong>; using it for unchecked exceptions has <strong>no effect</strong>.<br>2. <strong>throws only convinces the compiler</strong> but does not prevent abnormal termination.<br>3. If an exception is <strong>not handled by the caller</strong>, the program <strong>will still crash</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*UjckJy5ZiPv9tob0q6kH7w.png" /></figure><blockquote>In the above example, if we are removing any throws keyword the code won’t compile. compulsory we should use three throws statement and the main will delegate to jvm → default exception handler.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*GLd5zNeTY_ij0keTZSp8bQ.png" /><figcaption>\</figcaption></figure><h4>Case 02: The throws keyword used <strong>only in method and constructor signatures</strong></h4><p>In Java, the throws keyword can be used <strong>only in method and constructor signatures</strong>, but <strong>not at the class level</strong>. This is because <strong>exception handling is associated with method execution, not class definition</strong>.</p><p><strong>Example</strong>: Using throws in a Method</p><pre>import java.io.IOException;<br><br>public class ThrowsInMethod {<br>    static void readFile() throws IOException { // ✅ Allowed<br>        throw new IOException(&quot;File not found&quot;);<br>    }<br>    public static void main(String[] args) {<br>        try {<br>            readFile();<br>        } catch (IOException e) {<br>            System.out.println(&quot;Exception handled: &quot; + e.getMessage());<br>        }<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>Exception handled: File not found</pre><blockquote>We use throws in method signatures to indicate that the method <strong>may throw exceptions</strong>, and the caller must handle them.</blockquote><blockquote>Here, throws IOException tells the caller that readFile() may throw an IOException, which must be handled.</blockquote><p><strong>Example</strong>: Using throws in a Constructor</p><pre>class Example {<br>    Example() throws Exception { // ✅ Allowed<br>        throw new Exception(&quot;Constructor exception&quot;);<br>    }<br>}<br><br>public class ThrowsInConstructor {<br>    public static void main(String[] args) {<br>        try {<br>            Example obj = new Example(); // Must handle the exception<br>        } catch (Exception e) {<br>            System.out.println(&quot;Exception caught: &quot; + e.getMessage());<br>        }<br>    }<br>}</pre><p>Output:</p><pre>Exception caught: Constructor exception</pre><blockquote>Constructors can also use throws <strong>to declare exceptions that might be thrown during object creation</strong>.</blockquote><blockquote>Since Example() throws an exception, we must <strong>handle it when creating an object</strong>.</blockquote><p><strong>Why Can’t We Use </strong><strong>throws with Classes?</strong></p><ol><li>A class itself does not execute code — methods and constructors do.</li><li>Exception handling is associated with method execution, not class declaration.</li><li>The compiler enforces exception handling only on executable code.</li></ol><p><strong>Invalid Example</strong>: Using throws with a Class</p><pre>public class InvalidThrowsExample throws IOException { <br><br>// ❌ Compile-time error<br><br>}</pre><pre>Compile-time Error:<br><br>error: class, interface, or enum expected</pre><blockquote><strong>Key Takeaways</strong><br>1. throws can be used with methods to declare exceptions that must be handled.<br>2. throws can be used in constructors to indicate possible exceptions during object creation.<br>3. throws cannot be used at the class level because a class itself does not execute code.</blockquote><h4>Case 03: throws Only for Throwable Types</h4><p>In Java, the throws keyword is <strong>only applicable to exceptions</strong>, meaning it can be used <strong>only for classes that extend </strong><strong>Throwable</strong> (such as Exception and Error).</p><p>If we try to use throws for <strong>normal Java classes</strong> (e.g., String, Integer, Object), the <strong>compiler throws an error</strong> because these are <strong>not exceptions</strong>.</p><p><strong>Invalid Example</strong>: Using throws with a Non-Throwable Type</p><pre>public class InvalidThrows {<br>    static void testMethod() throws String { // ❌ Compile-time error<br>        throw new String(&quot;This is not allowed!&quot;);<br>    }<br><br>    public static void main(String[] args) {<br>        testMethod();<br>    }<br>}</pre><pre>Compile-time Error:<br><br>error: incompatible types: String cannot be converted to Throwable</pre><ul><li>throws <strong>must be followed by a subclass of </strong><strong>Throwable</strong>.</li><li>String is <strong>not</strong> a subclass of Throwable, so Java <strong>does not allow it</strong>.</li></ul><p><strong>Solution</strong>: Extend Throwable or Exception (for <strong>checked exception</strong>)<br>If we want to use throws, we must create a <strong>custom exception</strong> by extending Throwable or Exception.</p><pre>class MyCustomException extends Exception { // ✅ Must extend Throwable<br>    public MyCustomException(String message) {<br>        super(message);<br>    }<br>}<br><br>public class ValidThrowsExample {<br><br>    static void testMethod() throws MyCustomException { // ✅ Now it&#39;s valid<br>        throw new MyCustomException(&quot;Custom exception thrown!&quot;);<br>    }<br>    public static void main(String[] args) {<br>        try {<br>            testMethod();<br>        } catch (MyCustomException e) {<br>            System.out.println(&quot;Exception caught: &quot; + e.getMessage());<br>        }<br>    }<br>}</pre><p>Output:</p><pre>Exception caught: Custom exception thrown!</pre><p><strong>Now </strong><strong>MyCustomException is a valid exception type</strong>, so Java allows throws MyCustomException.</p><blockquote>Key Takeaways<br>1. The throws keyword <strong>must be used with classes that extend </strong><strong>Throwable</strong>.<br>2. <strong>Normal Java classes (like </strong><strong>String, </strong><strong>Integer) cannot be thrown</strong>, leading to a <strong>compile-time error</strong>.<br>3. To fix this, <strong>create a custom exception</strong> by extending Exception or RuntimeException.</blockquote><p><strong>Solution</strong>: Extend RuntimeException (for <strong>unchecked exception</strong>).</p><pre>class InvalidAgeException extends RuntimeException { // ✅ Extending RuntimeException<br>    public InvalidAgeException(String message) {<br>        super(message);<br>    }<br>}<br><br>public class RuntimeExceptionExample {<br>    static void checkAge(int age) {<br>        if (age &lt; 18) {<br>            throw new InvalidAgeException(&quot;Age must be 18 or above!&quot;); // ✅ No need for throws<br>        }<br>        System.out.println(&quot;You are eligible.&quot;);<br>    }<br>    public static void main(String[] args) {<br>        checkAge(16); // ❌ Throws RuntimeException at runtime<br>    }<br>}</pre><p>Output (Abnormal Termination):</p><pre>Exception in thread &quot;main&quot; InvalidAgeException: Age must be 18 or above!<br>    at RuntimeExceptionExample.checkAge(RuntimeExceptionExample.java:9)<br>    at RuntimeExceptionExample.main(RuntimeExceptionExample.java:14)</pre><blockquote>InvalidAgeException extends RuntimeException, which is <strong>unchecked</strong>.<br><strong>Unchecked exceptions do not require explicit handling</strong>; the program can continue execution if not caught.</blockquote><blockquote><strong>Key Takeaways</strong><br>1. RuntimeException and its subclasses are unchecked exceptions.<br>2. They do not require throws in method signatures.<br>3. If not handled, they cause abnormal termination at runtime.</blockquote><h4>Case 04: No <strong>possibility of a checked exception occurring</strong></h4><p>In Java, if there is <strong>no possibility of a checked exception occurring</strong> in a program, we <strong>cannot define a </strong><strong>catch block for that exception</strong>. If we do, we will get a <strong>compile-time error</strong> saying:</p><pre>🚨 &quot;Exception XXX is never thrown in the body of the corresponding try statement.&quot;</pre><p>However, <strong>this rule applies only to fully checked exceptions</strong> (exceptions that are not subclasses of RuntimeException and must be handled explicitly, e.g., IOException, SQLException).</p><p><strong>Example</strong>: Compile-time Error Due to Unnecessary Catch Block</p><pre>public class UnnecessaryCatchBlock {<br>    public static void main(String[] args) {<br>        try {<br>            System.out.println(&quot;This code does not throw IOException&quot;);<br>        } catch (IOException e) { // ❌ Compile-time error<br>            System.out.println(&quot;This will never execute!&quot;);<br>        }<br>    }<br>}</pre><pre>Compile-time Error:<br><br>error: exception java.io.IOException is never thrown in body of corresponding try statement</pre><ul><li>IOException is a <strong>checked exception</strong>, but <strong>no statement inside the </strong><strong>try block can cause it</strong>.</li><li>Since Java <strong>knows this at compile time</strong>, it <strong>does not allow unnecessary catch blocks</strong>.</li></ul><p><strong>Example</strong>: Valid Catch Block with a Checked Exception</p><p>If the try block contains a statement that <strong>might throw</strong> a checked exception, then the catch block is allowed:</p><pre>import java.io.*;<br><br>public class ValidCatchExample {<br>    public static void main(String[] args) {<br>        try {<br>            FileReader file = new FileReader(&quot;data.txt&quot;); // ✅ May throw IOException<br>        } catch (IOException e) { // ✅ No error, as IOException might occur<br>            System.out.println(&quot;File not found: &quot; + e.getMessage());<br>        }<br>    }<br>}</pre><p>Output (If file is missing):</p><pre>File not found: data.txt (No such file or directory)</pre><p>Now the catch block is valid because FileReader may throw IOException.</p><blockquote><strong>Key Takeaways</strong><br>1. If there is <strong>no possibility of a fully checked exception</strong>, defining a catch block for it <strong>causes a compile-time error</strong>.<br> 2. This <strong>rule applies only to fully checked exceptions</strong> (e.g., IOException, SQLException).<br> 3. <strong>Unchecked exceptions (</strong><strong>RuntimeException) do not follow this rule</strong>, and a catch block can be defined even if the exception never occurs.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*YWoEWY0UcE1mCD8B3sQmZA.png" /></figure><h3>Conclusion:</h3><p>1.<strong>throws is used to declare exceptions</strong> in a method signature, <strong>delegating</strong> the responsibility of handling exceptions to the caller.<br>2. It is <strong>required only for checked exceptions</strong>; using it for unchecked exceptions <strong>has no impact</strong>.<br> 3. The throws keyword <strong>does not handle exceptions</strong>—it simply informs the compiler that an exception might occur.<br> 4. Even if we declare throws, the program can still terminate abnormally if the exception is not handled by the caller.</p><blockquote><strong>What’s next?</strong><br>1. Exception handling keywords and each example<br>2. Various Possible Compile-Time Errors in Exception Handling<em>.<br>3. </em>Examples of Customized Exception (User-Defined Exception) in Java<em><br>3.1. </em><strong>Example 1</strong>: Custom Checked Exception<em><br>3.2. </em><strong>Example 2</strong>: Custom Unchecked Exception<br>4. Comprehensive Guide to 14 Common Java Exceptions<br>4.1. <strong>Programmatic Exceptions</strong> (Thrown explicitly by the programmer using <em>throw) <br>4.2. </em><strong>JVM Exceptions</strong> (Raised automatically by the JVM)</blockquote><p>Previous Article : — <a href="https://medium.com/@adityaharendramall/core-java-exceptional-handling-06-throw-and-its-cases-c75341663239">https://medium.com/@adityaharendramall/core-java-exceptional-handling-06-throw-and-its-cases-c75341663239</a></p><p>Next Article : — <a href="https://medium.com/@adityaharendramall/core-java-exceptional-handling-08-customized-exception-common-exceptions-7a500ea9e0d9">https://medium.com/@adityaharendramall/core-java-exceptional-handling-08-customized-exception-common-exceptions-7a500ea9e0d9</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbac4364b5f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Core Java — Exceptional Handling — 06 — Throw and it’s Cases]]></title>
            <link>https://medium.com/@adityaharendramall/core-java-exceptional-handling-06-throw-and-its-cases-c75341663239?source=rss-826dae311f2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c75341663239</guid>
            <category><![CDATA[throw]]></category>
            <category><![CDATA[core-java]]></category>
            <category><![CDATA[exception-handling]]></category>
            <dc:creator><![CDATA[Aditya Harendra Mall]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 16:53:49 GMT</pubDate>
            <atom:updated>2025-05-08T05:49:14.929Z</atom:updated>
            <content:encoded><![CDATA[<h3>Core Java — Exceptional Handling — 06 — Throw and it’s Cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3XF2i0-AzQ-PQzOIjihD2A.png" /></figure><blockquote><strong><em>Topics covered in this article</em></strong><em><br>1. Throw <br>2. </em>Case 01: throw and NullPointerException When e is Null<br>3. Case 02: Unreachable Code After throw Statement in Java<br>4. Case 03: throw Can Only Be Used with Throwable Types in Java<br>5. To make a normal Java class throwable, we must <strong>extend </strong><strong>RuntimeException</strong> or Exception. for unchecked exception.<br>6. To make a normal Java class throwable, we must <strong>extend </strong><strong>Exception </strong>for checked exception.</blockquote><h3>What is throw in Java?</h3><p>Sometimes we can create exception object explicitly and handover to the jvm manually for this we have to use throw keyword.</p><p>The throw keyword is used to <strong>explicitly throw an exception</strong> from a method or block of code. It is commonly used for <strong>manually triggering exceptions</strong> when a specific condition occurs.</p><p>Hence the main objective of throw keyword is to handover our created exception object to the jvm manually.</p><pre>throw new ExceptionType(&quot;Error message&quot;);<br><br>where throw - handover our created exception object to jvm manually<br>      new ExceptionType(&quot;Error message&quot;); - creation of Exception object manually.</pre><h4>Hence the result of the following two programs is exactly the same:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*aJRK0AwTlkq54ixyaUOXBg.png" /></figure><p><strong>Note:</strong> Best use of throw keyword is for user defined exception or customized exception.</p><h3>Case 01: <strong>throw and </strong><strong>NullPointerException When </strong><strong>e is Null</strong> 🚀</h3><p>In Java, when using the throw keyword to manually throw an exception, the <strong>exception object must not be null</strong>. If you try to throw null, the JVM will throw a <strong>NullPointerException (NPE)</strong> at runtime.</p><h4>Why does this happen?</h4><ul><li>The throw statement expects a <strong>valid exception object</strong> to be thrown.</li><li>Since e is null, when throw e; executes, <strong>there is no actual exception object to throw</strong>.</li><li>The JVM attempts to access null as an exception and <strong>throws a </strong><strong>NullPointerException instead</strong>.</li></ul><h4>🔹 Example: Throwing a Null Reference</h4><pre>public class NullThrowExample {<br>    public static void main(String[] args) {<br>        ArithmeticException e = null;  // Assigning null to an exception reference<br>        throw e; // ❌ This will cause NullPointerException<br>    }<br>}</pre><h4>🚨 Runtime Error:</h4><pre>Exception in thread &quot;main&quot; java.lang.NullPointerException<br>    at NullThrowExample.main(NullThrowExample.java:5)</pre><h4>🔹 Correct Way to Use throw</h4><p>To avoid this issue, always <strong>initialize the exception object properly</strong> before throwing it:</p><pre>public class ValidThrowExample {<br>    public static void main(String[] args) {<br>        ArithmeticException e = new ArithmeticException(&quot;Cannot divide by zero&quot;);<br>        throw e; // ✅ This is valid and will throw ArithmeticException<br>    }<br>}</pre><h4>✅ Output:</h4><pre>Exception in thread &quot;main&quot; java.lang.ArithmeticException: Cannot divide by zero</pre><h4>🔹 Handling null Before Throwing</h4><p>If you’re unsure whether an exception object might be null, <strong>check for null before throwing</strong>:</p><pre>public class SafeThrowExample {<br>    public static void main(String[] args) {<br>        ArithmeticException e = null;<br>        <br>        if (e == null) {<br>            throw new NullPointerException(&quot;Exception object is null!&quot;); // ✅ Handle it safely<br>        }<br>        throw e; // This won&#39;t execute due to the if condition<br>        }<br>    }</pre><h4>✅ Output:</h4><pre>Exception in thread &quot;main&quot; java.lang.NullPointerException: Exception object is null!</pre><blockquote><strong>Key Takeaways</strong></blockquote><blockquote>Throwing null as an exception <strong>causes </strong><strong>NullPointerException at runtime</strong>.</blockquote><blockquote>Always <strong>initialize an exception object</strong> before throwing it.</blockquote><blockquote>To avoid this, <strong>check for null before throwing</strong> an exception.</blockquote><h3>Case 02: <strong>Unreachable Code After </strong><strong>throw Statement in Java</strong></h3><p>In Java, when a throw statement is executed, it <strong>immediately terminates the method</strong> by throwing an exception. Any statement <strong>written after </strong><strong>throw in the same block</strong> becomes <strong>unreachable</strong>, leading to a <strong>compile-time error</strong>.</p><h4>Example: Unreachable Code After throw</h4><pre>public class UnreachableCodeExample {<br>    public static void main(String[] args) {<br>        System.out.println(&quot;Before throw&quot;);<br>        throw new ArithmeticException(&quot;Division by zero&quot;); <br>        System.out.println(&quot;This statement is unreachable!&quot;); // ❌ Compile-time error<br>    }<br>}</pre><h4>Compile-time Error:</h4><pre>error: unreachable statement<br>        System.out.println(&quot;This statement is unreachable!&quot;);<br>                        ^</pre><h4>Why does this happen?</h4><ul><li>The throw statement <strong>immediately exits the method</strong> by throwing an exception.</li><li>The compiler <strong>knows</strong> that any code after throw will <strong>never be executed</strong>, leading to an <strong>&quot;unreachable statement&quot;</strong> error.</li></ul><h4>🔹 How to Fix It?</h4><p>If you need to execute code after an exception, use <strong>try-catch-finally</strong>:</p><pre>public class ReachableCodeExample {<br>    public static void main(String[] args) {<br>        try {<br>            throw new ArithmeticException(&quot;Division by zero&quot;);<br>        } catch (ArithmeticException e) {<br>            System.out.println(&quot;Exception handled: &quot; + e.getMessage());<br>        }<br>        System.out.println(&quot;This statement is now reachable.&quot;);<br>    }<br>}</pre><h4>✅ Output:</h4><pre>Exception handled: Division by zero<br>This statement is now reachable.</pre><h4>🔹 Special Case: Unreachable Code Inside if-else</h4><pre>public class Test {<br>    public static void main(String[] args) {<br>        if (true) {<br>            throw new RuntimeException(&quot;Error occurred&quot;);<br>        }<br>        System.out.println(&quot;Unreachable code!&quot;); // ❌ Compile-time error<br>    }<br>}</pre><p>Since if (true) <strong>always executes</strong>, the throw statement is <strong>guaranteed to run</strong>, making the next statement unreachable.</p><blockquote><strong><em>Key Takeaways<br></em></strong><em>1</em><strong><em>. </em>throws immediately terminates execution</strong> in a method.<br>2. Any statement <strong>after </strong><strong>throw in the same block is unreachable</strong> → <strong>Compile-time error</strong>.<br>3. To avoid this error, handle exceptions using <strong>try-catch-finally</strong>.<br>4. If throw is inside <strong>if (true)</strong>, code after it becomes <strong>unreachable</strong>.</blockquote><h3>Case 03: <strong>throw Can Only Be Used with </strong><strong>Throwable Types in Java</strong></h3><p>In Java, the throw keyword <strong>can only be used to throw objects that are instances of </strong><strong>Throwable (or its subclasses like </strong><strong>Exception and </strong><strong>Error)</strong>. If we try to throw a <strong>normal Java object</strong> (like String, Integer, or any non-Throwable class), we get a <strong>compile-time error</strong>:</p><pre>error: incompatible types: String cannot be converted to Throwable</pre><h4>Example: Compile-time Error When Throwing a Non-Throwable Object</h4><pre>public class InvalidThrowExample {<br>    public static void main(String[] args) {<br>        throw &quot;This is an exception&quot; or new InvalidThrowExample(); // ❌ Compile-time error: incompatible types<br>    }<br>}<br><br>public class InvalidThrowExample {<br>    public static void main(String[] args) {<br>        throw new InvalidThrowExample(); // ❌ Compile-time error: incompatible types<br>    }<br>}</pre><h4>Compile-time Error:</h4><pre>error: incompatible types: String cannot be converted to Throwable<br>        throw &quot;This is an exception&quot;;<br>              ^<br>error: incompatible types: InvalidThrowExample cannot be converted to Throwable<br>        throw new InvalidThrowExample();<br>              ^</pre><ul><li>Java does <strong>not allow throwing normal objects</strong> like String because they do not extend Throwable.</li><li>Only objects that are <strong>instances of </strong><strong>Throwable (Exception or Error classes)</strong> can be thrown.</li></ul><h3>How to Fix It? Extend RuntimeException (unchecked exception)</h3><p>To make a normal Java class throwable, we must <strong>extend </strong><strong>RuntimeException</strong> or Exception.</p><h4>Correct Example: Creating a Custom Exception (UnChecked Exception)</h4><pre>// Custom exception class extending RuntimeException<br>class MyCustomException extends RuntimeException {<br>    public MyCustomException(String message) {<br>        super(message); // Pass message to RuntimeException constructor<br>    }<br>}<br><br>public class CustomThrowExample {<br>    public static void main(String[] args) {<br>        throw new MyCustomException(&quot;This is a custom runtime exception!&quot;);<br>    }<br>}</pre><h4>Output:</h4><pre>Exception in thread &quot;main&quot; MyCustomException: This is a custom runtime exception!<br>    at CustomThrowExample.main(CustomThrowExample.java:9)</pre><blockquote><strong>Why does this work?</strong></blockquote><blockquote>MyCustomException extends RuntimeException, which is a subclass of Throwable.</blockquote><blockquote>Since Java allows throwing any subclass of Throwable, this <strong>compiles and runs correctly</strong>.</blockquote><h4>Another Example: Extending Exception (Checked Exception)</h4><p>If you want a <strong>checked exception</strong>, extend Exception instead of RuntimeException:</p><pre>class CheckedException extends Exception {<br>    public CheckedException(String message) {<br>        super(message);<br>    }<br>}<br><br>public class CheckedThrowExample {<br>    public static void main(String[] args) throws CheckedException {<br>        throw new CheckedException(&quot;This is a custom checked exception!&quot;);<br>    }<br></pre><h4>✅ Output:</h4><pre>Exception in thread &quot;main&quot; CheckedException: This is a custom checked exception!<br>    at CheckedThrowExample.main(CheckedThrowExample.java:9)</pre><h4><strong>Why </strong><strong>throws CheckedException is required?</strong></h4><blockquote>Since CheckedException extends Exception, it is a <strong>checked exception</strong>.</blockquote><blockquote>Java <strong>forces</strong> us to either <strong>handle it using </strong><strong>try-catch</strong> or <strong>declare it in the method signature using </strong><strong>throws</strong>.</blockquote><blockquote>The throw keyword <strong>only works with </strong><strong>Throwable types</strong> (i.e., subclasses of Exception or Error).</blockquote><blockquote>If we try to throw a normal object (like String or Integer), Java gives a <strong>compile-time error</strong> (incompatible types).</blockquote><blockquote>To make a class throwable, we must <strong>extend </strong><strong>RuntimeException</strong> (for unchecked exceptions) or <strong>Exception</strong> (for checked exceptions).</blockquote><h3>Conclusion:</h3><ol><li><strong>throw</strong> is used to <strong>explicitly throw an exception</strong> inside a method or block.</li><li>2. Any statement <strong>after </strong><strong>throw becomes unreachable</strong>, leading to a <strong>compile-time error</strong>.</li><li><strong>Only objects of </strong><strong>Throwable or its subclasses</strong> can be thrown; otherwise, a <strong>compile-time error occurs</strong>.</li></ol><blockquote><strong>What’s Next</strong><br>1.</blockquote><p><strong>Previous Article</strong> : — <a href="https://medium.com/@adityaharendramall/core-java-exceptional-handling-05-finally-block-combination-of-try-catch-and-finally-3091804aa22a">https://medium.com/@adityaharendramall/core-java-exceptional-handling-05-finally-block-combination-of-try-catch-and-finally-3091804aa22a</a></p><p><strong>Next Article</strong> : — <a href="https://medium.com/@adityaharendramall/core-java-exceptional-handling-07-throws-and-its-cases-bbac4364b5f4">https://medium.com/@adityaharendramall/core-java-exceptional-handling-07-throws-and-its-cases-bbac4364b5f4</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c75341663239" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>