When using multiple catch statements in Java, it's crucial to position exception subclasses before their superclasses. This is because a catch statement for a superclass will intercept exceptions of that type, including any of its subclasses, rendering the subclass catch statement unreachable if placed afterward. For example, consider the following program: /* This program contains an error. A subclass must come before its superclass in a series of catch statements. If not, unreachable code will be created and a compile-time error will result. */ class SuperSubCatch { public static void main(String args[]) { try { int a = 0; int b = 42 / a; } catch(Exception e) { System.out.println("Generic Exception catch."); } /* This catch is never reached because ArithmeticException is a subclass of Exception. */ catch(ArithmeticException e) { // ERROR – unreachable System.out.println("This is never reached."); } } } If you compile this program, you will encounter an error message indicating that the second catch statement is unreachable due to the first catch statement already handling all Exception-based errors, including ArithmeticException. To resolve this issue, simply reverse the order of the catch statements. This adjustment ensures that the subclass catch statement is evaluated first, allowing it to function correctly.
Java Exception Handling: Subclass Catch Statements Before Superclass
More Relevant Posts
-
In Java, method overloading happens when a class (or interface) declares multiple methods with the same name but different parameter lists. ✔️ Different number of parameters ✔️ Different parameter types ✔️ Different order of parameter types (use carefully) A method’s signature in Java is defined as: method name + parameter types The return type is NOT part of the method signature. That means this will not compile: int parse(String s) { } long parse(String s) { } // ❌ duplicate method Why? Because the compiler resolves overloaded methods at compile time, and method calls don’t include return type information. Also worth noting: ✔️ static, final, access modifiers don’t affect signature uniqueness ✔️ Varargs are treated as arrays (foo(String...) ≈ foo(String[])) If two methods differ only by return type, Java will treat them as duplicates.
To view or add a comment, sign in
-
Have you ever wondered how Java's HashSet actually works under the hood to guarantee unique elements? To understand how a HashSet ensures no duplicates, the secret doesn't actually lie within the "Set" itself, but rather in the HashMap. In fact, behind the scenes, every time you instantiate a HashSet, Java creates a HashMap to manage the data. Keep in mind that in a HashMap, you always have a Key and a Value. In a HashSet, the implementation stores your object as the Key and fills the Value slot with a dummy static constant just to occupy the space, since the HashMap API requires both parameters. Because map keys must be unique, the HashSet inherits this constraint for free. To ensure that HashMap keys do not repeat, Java utilizes the hashCode. Think of it as a barcode; with this number, Java knows exactly which bucket that object belongs to. It is possible for two different objects to have the same hashCode. When this occurs, we call it a collision. To resolve this, Java then uses the equals method, which in turn compares the actual content of the objects to verify if they are truly identical.
To view or add a comment, sign in
-
Important question: What is volatile in Java? volatile is a keyword used with variables to guarantee visibility and ordering in a multithreaded environment. It ensures that changes made by one thread are immediately visible to other threads. Problem Without volatile (Visibility Issue) In Java, each thread can cache variables locally (CPU cache / register). class Example { boolean running = true; void stop() { running = false; } void run() { while (running) { // infinite loop possible } } } ❌ One thread updates running = false ❌ Other thread may never see the update ⸻ ✅ Solution: Using volatile class Example { volatile boolean running = true; void stop() { running = false; } void run() { while (running) { // stops correctly } } } ✔ Change is immediately visible to all threads
To view or add a comment, sign in
-
One very common perception is that Java supports pass by value for primitive type and pass by reference for objects semantics. However in reality, Java supports only pass by value semantics. In java objects are not passed by reference, but object references are passed by value. Object reference is just another name to pointer for the object. When you define something like CustomObj myObj; in java, you are creating a pointer to the object, not the actual object. Hence, passing it in function parameter, passes the pointer to object by value. Read about in detail in this blog: https://lnkd.in/grfDhPrx Please share you feedback.
To view or add a comment, sign in
-
Fun with pattern matching scope in Java 21 I’m switching to Java 21 and I stumbled upon a comment under 2023 article that was good to share as Java puzzle: By coincidence, one of our projects, is still on Java 11. At the same time, some dependencies have moved to Java 17. So I ended up by using OpenRewrite to backport modern Java features. Along the way, I learned many interesting things. For example, that this is perfectly valid Java: if (!(obj instanceof String str)) { throw new IllegalArgumentException(); } System.out.println(str.length()); And also this (yes, these are two different str variables): if (!(obj instanceof String str)) { Integer str = null; System.out.println(str); } else { System.out.println(str); } Now let’s play a game. Without running this code or copying it into an IDE, can you confidently tell in which cases str is available in the else branch on attached screenshot? Still too easy? Add more conditions. Nest a few "if". Use multiple pattern variables. Go wild. At some point, str starts behaving like a Heisenberg variable: until you paste the code into an IDE, you can’t be 100% sure about its scope In the end, I wrote more tests than actual transformation code: tests: https://lnkd.in/e4PncArw transformation: https://lnkd.in/emqktnFC Comment source: https://lnkd.in/eP-H2Cza
To view or add a comment, sign in
-
-
✅ Checked vs ❌ Unchecked Exceptions in Java — Explained Simply In Java, exceptions help us handle unexpected situations gracefully. But not all exceptions are the same — they fall into two key categories: ✔ Checked Exceptions These are checked at compile time. Java forces you to either handle them using try-catch or declare them with throws. 📌 Examples: IOException, SQLException 💡 Use Case: When the failure is expected and recoverable (like file not found, DB unavailable). ❌ Unchecked Exceptions These are not checked at compile time. They usually indicate programming errors and happen at runtime. 📌 Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException 💡 Cause: Often due to logic flaws in code. 🧠 Quick Summary Checked at Compile Time? Type Common Source Class ✔ Checked ✅ Yes External factors Exception (not RuntimeException) ❌ Unchecked ❌ No Programming errors RuntimeException 🚀 Key Takeaway Use checked exceptions for recoverable scenarios Avoid overusing them — or your code becomes noisy Fix unchecked exceptions by improving logic Well-designed exception handling = cleaner, safer, and more reliable code 💪 What’s your take — checked or unchecked? 🙂
To view or add a comment, sign in
-
🔑 Java Objects vs References: The Clear Difference =>Many developers often confuse objects and references in Java. Let’s break it down in simple terms 👇 🟢 Object Definition: A real instance created in memory. Creation: Built using the new keyword. Storage: Lives in heap memory. Contains: Actual data (fields) and behavior (methods). Example: Dog d = new Dog(); // "new Dog()" is the object 🟡 Reference Definition: A variable that points to an object’s memory address. Storage: Lives in stack memory. Contains: Only the pointer (address), not the actual data. Example: Dog d = new Dog(); // "d" is the reference 🧠 Analogy Object = House 🏠 (the real thing built in memory). Reference = Address 📍 (the pointer that tells you where the house is). Without a house, an address is meaningless. Without an address, the house is unreachable. ⚠️ Special Case You can declare a reference without creating an object: Dog d; // reference only, no object yet Calling d.sound() here will throw a NullPointerException, because the reference doesn’t point to any object. 🎯 Takeaway Objects are the real entities in heap memory. References are the handles we use to access those objects. Understanding this distinction is crucial for mastering Java memory management and avoiding pitfalls like NullPointerException. 💡 Think of it this way: Objects live in heap, references live in stack. Object is the house, reference is the address.
To view or add a comment, sign in
-
-
📘 Core Java Day 14 | Different Ways to Create Objects in Java In Java, creating objects is not limited to just using the new keyword. While new is the most common ways is there, Here are the main ones: 1 Using new keyword - The standard way to create an object by calling a constructor. 2 Using Factory / Static Factory Methods - Object creation logic is moved to a method, which helps in loose coupling and better design. Example: Integer.valueOf() 3 Using Cloning - Creates a copy of an existing object without calling the constructor. 4 Using Reflection - Objects are created at runtime using class metadata. Commonly used in frameworks. 5 Using Deserialization - Objects are created from a stream (file or network), bypassing constructors. object creation in Java is about design, flexibility, and control
To view or add a comment, sign in
-
-
Heap vs Stack memory in java ---------------------------------- The stack and heap are two areas of memory used by a program, but they serve different purposes ● Stack memory is used for method execution. ● It stores local variables, method parameters, and method call information. ● Each thread has its own stack, so stack memory is thread-safe. ● Stack memory is fast, and memory is automatically freed when a method finishes execution. ● Heap memory is used to store objects and class instances. ● It is shared across all threads, so it is not thread-safe by default. ● Objects in heap memory live until they are no longer referenced, and then the Garbage Collector removes them. Stack → method calls and local variables Heap → objects and instance variables Also, stack memory is smaller and faster, while heap memory is larger but slower compared to stack. Simple Example --------------- void demo() { int x = 10; // stored in Stack Student s = new Student(); // reference in Stack, object in Heap } You can explain this as: ➤ The variable x is stored directly in the stack. ➤ The reference s is in the stack, but the actual Student object is created in the heap. If this article helped you understand the topic, please like and share and follow me for more updates 👏
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development