Ever wondered if Java’s checked exceptions can be… bypassed? I explored an interesting approach using generics to influence how checked exceptions are treated by the compiler. Here’s the interesting part: catch (Exception e) { Task.<RuntimeException>throwAs(e); } At compile time: The compiler believes we are throwing a RuntimeException (unchecked), so it doesn’t force us to handle or declare it. At runtime: Due to type erasure, the JVM simply throws the original exception which can still be a checked exception like InterruptedException. The trick lies in this method: @SuppressWarnings("unchecked") public static <T extends Throwable> void throwAs(Throwable t) throws T { throw (T) t; } This works because: • Generics are erased at runtime • Checked exceptions are enforced only by the compiler So effectively: → We bypass Java’s checked exception mechanism → Without breaking any JVM rules This pattern is often called a “Sneaky Throw” and is even used internally by tools like Lombok (@SneakyThrows). Not something to use casually in production, but a great way to understand how Java’s type system and exception handling really work under the hood. #Java #Programming #Generics #ExceptionHandling
Bypassing Java Checked Exceptions with Generics
More Relevant Posts
-
Every Java program uses two memory areas at runtime: the stack and the heap. They serve very different purposes and understanding the distinction is one of those things that separates developers who write code from developers who understand what their code actually does. The stack is where method calls live. Every time you call a method, the JVM pushes a new frame onto the stack containing local variables, parameters, and the return address. When the method finishes, the frame gets popped off. It's fast because there's no searching involved, just a pointer moving up and down. Each thread gets its own stack, so there's no synchronization overhead. The heap is shared memory where objects live. When you write new Person(), that object gets allocated on the heap, and a reference (essentially a pointer) gets stored on the stack. This is why Java is "pass by value" but it feels like "pass by reference" for objects. You're passing the value of the reference, not the object itself. The garbage collector only operates on the heap. It periodically scans for objects that no longer have any references pointing to them and reclaims that memory. The heap is further divided into generations. Young Gen handles short-lived objects (most objects die young), and Old Gen stores objects that survived multiple GC cycles. This generational approach is why modern JVMs can handle millions of allocations efficiently. Stack overflows happen when you have too many nested method calls (usually infinite recursion). OutOfMemoryErrors happen when the heap runs out of space. Knowing which memory area is involved tells you exactly where to look when debugging. #java #coding #programming
To view or add a comment, sign in
-
-
💡 𝗛𝗼𝘄 𝗝𝗮𝘃𝗮 𝗪𝗼𝗿𝗸𝘀 𝗨𝗻𝗱𝗲𝗿 𝘁𝗵𝗲 𝗛𝗼𝗼𝗱 — 𝗙𝗿𝗼𝗺 𝗖𝗼𝗱𝗲 𝘁𝗼 𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 Ever wondered what happens when you run a Java program? Here’s a simple breakdown: 1️⃣ 𝗪𝗿𝗶𝘁𝗲 𝗖𝗼𝗱𝗲 You write Java source code in a `.java` file. 2️⃣ 𝗖𝗼𝗺𝗽𝗶𝗹𝗲 The Java compiler (`javac`) converts `.java` file into **bytecode** (`.class` file). 3️⃣ 𝗖𝗹𝗮𝘀𝘀 𝗟𝗼𝗮𝗱𝗲𝗿 JVM loads the `.class` bytecode into memory. 4️⃣ 𝗕𝘆𝘁𝗲𝗰𝗼𝗱𝗲 𝗩𝗲𝗿𝗶𝗳𝗶𝗲𝗿 Checks for security issues and ensures code follows Java rules. 5️⃣ 𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 JVM executes bytecode using: • Interpreter (line by line execution) • JIT Compiler (converts to native machine code for faster performance) 👉 Flow: Java Code → Compiler → Bytecode → JVM → Machine Code → Output ✨ This is why Java is platform independent: "Write Once, Run Anywhere" #Java #JVM #Programming #JavaDeveloper #Coding #SoftwareDevelopment #TechLearning
To view or add a comment, sign in
-
-
🚫 Why Java Disallows Multiple Inheritance – The Diamond Problem Explained! Ever wondered why Java doesn’t support multiple inheritance with classes? 🤔 The answer lies in something called the Diamond Problem. 🔷 Imagine this: A class (Child) inherits from two parent classes (Parent A & Parent B), and both of them inherit from a common class (Object). Now, what happens if both parents have the same method? 👉 The child class gets duplicate methods 👉 The compiler gets confused 👉 And you get a compilation error ❌ 💥 This leads to ambiguity: Which method should the child use? Parent A’s or Parent B’s? 🔍 Key Insights: ✔ Every Java class already extends the Object class ✔ Multiple inheritance can lead to duplicate method injection ✔ Identical method signatures create conflicts the compiler can’t resolve ✔ Java follows a “zero tolerance for ambiguity” approach 💡 How Java Solves This? Instead of multiple inheritance with classes, Java uses: 👉 Interfaces (with default methods) 👉 Clear method overriding rules This ensures: ✅ Better code clarity ✅ No ambiguity ✅ Easier maintainability 🔥 Takeaway: Java prioritizes simplicity and reliability over complexity — and avoiding the Diamond Problem is a perfect example of that design philosophy. #TAPAcademy #Java #OOP #Programming #SoftwareDevelopment #Coding #JavaDeveloper #TechConcepts #LearningJourney
To view or add a comment, sign in
-
-
Modern Java quietly made the Visitor pattern relevant again. Sealed classes changed the tradeoffs. It might be time to revisit Visitor. I wrote about why Visitor still makes sense if you're using Java 17–20: https://lnkd.in/dPkpgqtb
To view or add a comment, sign in
-
ERRORS & EXCEPTIONS IN JAVA — SIMPLE & CLEAR WHAT IS AN ERROR? An Error is a serious problem that occurs due to system failure, and we cannot handle it in our program. TYPES OF ERRORS & WHY THEY OCCUR Compile-Time Error • Occurs during compilation • Happens due to wrong syntax (faulty grammar) Examples: - Missing semicolon - Wrong keywords - Incorrect method syntax Runtime Error • Occurs during execution • Happens due to lack of system resources Examples: - StackOverflowError → infinite method calls - OutOfMemoryError → memory is full WHY ERRORS OCCUR (IN ONE LINE): Because of system limitations or wrong program structure WHAT IS AN EXCEPTION? An Exception is a problem caused by the program logic, and we can handle it using try-catch. TYPES OF EXCEPTIONS & WHY THEY OCCUR Checked Exception (Compile Time) • Checked by compiler • Must handle using try-catch or throws WHY IT OCCURS: Because we are using methods that declare exceptions (ducking), so Java forces us to handle or pass them Examples: - IOException → file not found - InterruptedException → thread interruption Unchecked Exception (Runtime) • Not checked by compiler • Occurs during execution WHY IT OCCURS: Because of logical mistakes in program Examples: - ArithmeticException → divide by zero - NullPointerException → using null object FINAL ONE-LINE DIFFERENCE Error → System problem Exception → Programmer mistake Simple Understanding: Errors = Cannot fix easily Exceptions = Can handle and continue program #Java #ExceptionHandling #Programming #Coding #Developers #JavaBasics
To view or add a comment, sign in
-
💻 Interface in Java — The Power of Abstraction 🚀 If you want to write flexible, scalable, and loosely coupled code, understanding Interfaces in Java is a must 🔥 This visual breaks down interfaces with clear concepts and real examples 👇 🧠 What is an Interface? An interface is a blueprint of a class that defines a contract. 👉 Any class implementing it must provide the method implementations 🔍 Key Characteristics: ✔ Methods are public & abstract by default ✔ Cannot be instantiated ✔ Supports multiple inheritance ✔ Variables are public, static, final ⚡ Why Interfaces? ✔ Achieve abstraction ✔ Enable loose coupling ✔ Improve code flexibility ✔ Allow multiple inheritance 🧩 Advanced Features (Java 8+): 🔹 Default Methods 👉 Provide implementation inside interface default void info() { System.out.println("This is a shape"); } 🔹 Static Methods 👉 Called using interface name static int add(int a, int b) { return a + b; } 🔹 Private Methods 👉 Reuse logic inside interface 🚀 Real Power: 👉 One interface → multiple implementations 👉 Same method → different behavior (Polymorphism) 🎯 Key takeaway: Interfaces are not just syntax — they define how different parts of a system communicate and scale efficiently. #Java #OOP #Interface #Programming #SoftwareEngineering #BackendDevelopment #Coding #100DaysOfCode #Learning
To view or add a comment, sign in
-
-
🚀 Day -2 JDK, JRE, JVM Journey with Frontlines EduTech (FLM) and Fayaz S JDK:- 👉 JDK means Java Development kit 👉 Which is collection of the following components 1. Java compiler 2. JVM, 3. Java library ** Simple:- JDK = JRE+ Development kit JRE:- JRE means Java Runtime Environment Which is collection of Java library and JVM JRE is an internal partition of JDK **Simple:- JRE = JVM+library needed to run program JVM:- JVM means Java virtual machine It runs Java Byte code It converts Byte code into machine code and makes Java platform Independent. ** Simple:- JVM ----> Engine that runs Java program. JVM has 3 components 1. CLSS 2. Memory management 3. Execution engine 1.CLSS ----> class loader subsystem load all .class files Verifies all .class filed Links Initialises 2. Memory management:- 👉 Method area ---> static variable, static methods ----> Class meta data link Name, package, parent classes 👉 Heap Area:- ---> Instance Variable ----> objects references 👉 Static area:- Collapse time to time It is stores local variables Threads information is have 👉 Program Counters:- Pointing Current instructions Update next instruction 👉 Native stack area:- Related to other languages (C, C++) 3. Execution engine:- 👉 Interprtor Execute the .class file 👉 JIT compiler Just in time compiler Finds the repetitive code Executes in a single shot Hybrid Language 👉 Garbage collector Collection all unused references/ memoryfreeUp. #corejava #JDK #JRE #JVM #FrontlinesEduTech
To view or add a comment, sign in
-
-
Stop being confused by Java Collections. Here's the whole picture in 30 seconds 👇 Most developers use ArrayList for everything. But Java gives you a powerful toolkit — if you know when to use what. 📋 LIST — When ORDER matters & duplicates are OK ArrayList → Fast reads ⚡ LinkedList → Fast inserts/deletes 🔁 🔷 SET — When UNIQUENESS matters HashSet → Fastest, no order LinkedHashSet → Insertion order TreeSet → Sorted order 📊 🔁 QUEUE — When the SEQUENCE of processing matters PriorityQueue → Process by priority ArrayDeque → Fast stack/queue ops 🗺️ MAP — When KEY-VALUE pairs matter HashMap → Fastest lookups 🔑 LinkedHashMap → Preserves insertion order TreeMap → Sorted by keys 🧠 Quick Decision Rule: Need duplicates? → List Need uniqueness? → Set Need FIFO/Priority? → Queue Need key-value? → Map The right collection = cleaner code + better performance. 🚀 Save this. Share it with a dev who still uses ArrayList for everything. 😄 #Java #Collections #Programming #SoftwareDevelopment #100DaysOfCode #JavaDeveloper #Coding #TechEducation #SDET
To view or add a comment, sign in
-
-
I recently explored a subtle but important concept in Java constructor execution order. Many developers assume constructors simply initialize values, but the actual lifecycle is more complex. In this article, I explain: • The real order of object creation • Why overridden methods can behave unexpectedly • A common bug caused by partial initialization This concept is especially useful for interviews and writing safer object-oriented code. Medium Link: https://lnkd.in/gtRhpdfP #Java #OOP #SoftwareDevelopment #Programming
To view or add a comment, sign in
-
Day 11/100 – Java Practice Challenge 🚀 Continuing my #100DaysOfCode journey with another important Java concept. 🔹 Topic Covered: Compile-time vs Runtime Polymorphism 💻 Practice Code: 🔸 Compile-time Polymorphism (Method Overloading) class Calculator { int add(int a, int b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } } 🔸 Runtime Polymorphism (Method Overriding) class Animal { void sound() { System.out.println("Animal sound"); } } class Cat extends Animal { @Override void sound() { System.out.println("Cat meows"); } } public class Main { public static void main(String[] args) { // Compile-time Calculator c = new Calculator(); System.out.println(c.add(10, 20)); System.out.println(c.add(10, 20, 30)); // Runtime Animal a = new Cat(); a.sound(); } } 📌 Key Learnings: ✔️ Compile-time → method decided at compile time ✔️ Runtime → method decided at runtime ✔️ Overloading vs Overriding difference 🎯 Focus: Understanding how Java resolves method calls 🔥 Interview Insight: Difference between compile-time and runtime polymorphism is one of the most frequently asked Java interview questions. #Java #100DaysOfCode #MethodOverloading #MethodOverriding #Polymorphism #JavaDeveloper #Programming #LearningInPublic
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