What happens when an exception is thrown inside a finally block? • We all learn early that finally always executes • But there’s a dangerous edge case many developers miss Consider this: • An exception occurs in the try block • Control moves to finally • Another exception is thrown inside finally What Java actually does: • The exception from finally overrides the original exception • The original exception is silently lost • Debugging becomes painful because the real cause disappears Why this is risky: • You think cleanup is handled safely • But the real failure gets masked Real-world scenario: • DB query fails → exception thrown • finally tries to close the connection • close() throws another exception • You only see the cleanup failure, not the DB issue Best practices: • Never throw new exceptions from finally • Keep finally simple and safe • Use try-with-resources whenever possible • Log inside finally, don’t propagate Key takeaway: • finally is for cleanup — not logic, not errors, not control flow If this surprised you, you’re not alone. #Java #ExceptionHandling #BackendDevelopment #CleanCode #LearningInPublic
Java Exception Handling Gotcha: Finally Blocks and Exception Overriding
More Relevant Posts
-
🧩⚡ COLLECTORS.TEEING(): TWO AGGREGATIONS, ONE STREAM PASS 🔸 TLDR ▪️ Need two aggregations? teeing() does it in one collect with a clean immutable merge. 🔸 THE PROBLEM Ever needed two aggregations (ex: count + sum) on the same stream? The “classic” approach often streams the data twice — simple, but not always ideal. 🔸 CODE: OLD VS MODERN // ✕ Java 8: two passes long count = items.stream().count(); double sum = items.stream() .mapToDouble(Item::price) .sum(); var result = new Stats(count, sum); // ✓ Java 12+: one pass with teeing() var result = items.stream().collect( Collectors.teeing( Collectors.counting(), Collectors.summingDouble(Item::price), Stats::new ) ); 🔸 SEE A PROBLEM WITH THIS CODE? LET US KNOW 👀 Hint: there’s a subtle one depending on what items is… 😉 🔸 WHY THE MODERN WAY WINS ▪️ ⚡ Single pass: stream once, aggregate twice ▪️ 🧩 Composable: mix any 2 collectors (min/max, summary stats, grouping, etc.) ▪️ 🔒 Immutable result: merge straight into a record / value object 🔸 HOW IT WORKS (IN 1 SENTENCE) Collectors.teeing() routes each element to two downstream collectors, then merges both results using your merger function (Stats::new here). 🔸 TAKEAWAYS ▪️ Prefer teeing() when you want two results from one stream without mutable accumulators ▪️ Great fit for Stats/DTO/record building ▪️ Still keep readability in mind: for tiny lists, two passes can be totally fine ✅ #Java #Java12 #Streams #Collectors #FunctionalProgramming #CleanCode #Performance #BackendDevelopment #JVM src: https://lnkd.in/ezn22fFC Go further with Java certification: Java👇 https://lnkd.in/eZKYX5hP Spring👇 https://lnkd.in/eADWYpfx SpringBook👇 https://bit.ly/springtify JavaBook👇 https://bit.ly/jroadmap
To view or add a comment, sign in
-
-
It's 2am. Production is down. Your users can't access their data. Your boss is pinging you. You stare at the error: NullPointerException at line 247 And you think: I tested this. It compiled. How. You trace it back. Find the method. It looked fine. It looked safe. Java never said a word. It let you write it. It let you compile it. It let you ship it. It waited. And then it shot you in the foot. That 2am panic isn't a skill issue. It's a language issue. Java compiles your code. It does not verify your assumptions. Rust is different. A null reference? Doesn't exist. An unhandled case? Won't compile. A value that might be missing? You handle it, or it doesn't build. You fight the compiler at 2pm. Not your users at 2am. Some foundations cannot be patched. They have to be replaced. Drop a 🦀 if you've been that dev at 2am. Follow me. #java #rust
To view or add a comment, sign in
-
-
Bean Lifecycle in Spring : A Spring Bean lifecycle describes what happens to a bean from creation to destruction. 🔄 Bean Lifecycle – Step by Step: 1️⃣ Bean Creation ➡ Spring creates the object 2️⃣ Dependency Injection ➡ Required dependencies are injected 3️⃣ Initialization ➡ Bean is ready to use 4️⃣ Business Logic Execution ➡ Bean is used in the application 5️⃣ Bean Destruction ➡ Bean is destroyed when the application stops 🧠 How Spring Manages This? Spring’s IoC Container controls the entire lifecycle automatically. 📌 Common Lifecycle Hooks @PostConstruct → runs after bean creation @PreDestroy → runs before bean destruction @Component class MyBean { @PostConstruct public void init() { System.out.println("Bean Initialized"); } @PreDestroy public void destroy() { System.out.println("Bean Destroyed"); } } 💡 Simple Way to Remember Create → Inject → Initialize → Use → Destroy #Spring #SpringBoot #BeanLifecycle #Java #LearningInPublic #BackendDevelopment
To view or add a comment, sign in
-
-
New to Spring Boot? You'll see these annotations in every project. Here's what they actually do: @SpringBootApplication → Entry point. Combines @Configuration, @EnableAutoConfiguration, @ComponentScan @RestController → Marks a class as an HTTP request handler that returns data (not views) @Service → Business logic layer. Spring manages it as a bean @Repository → Data access layer. Also enables Spring's exception translation @Autowired → Inject a dependency automatically (prefer constructor injection instead) @GetMapping / @PostMapping / @PutMapping / @DeleteMapping → Maps HTTP methods to your handler methods @RequestBody → Deserializes JSON from request body into a Java object @PathVariable → Extracts values from the URL path Bookmark this. You'll refer back to it constantly. Which annotation confused you the most when starting out? 👇 #Java #SpringBoot #Annotations #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
🚨 A Small File That Caused a Big Headache: classpath.txt Recently, I ran into an issue while working on a large Java project built with Maven. I was trying to start the application using an external dependency — the H2 database driver. Everything seemed correct. I followed the existing instructions carefully. I even executed a bash command to copy the H2 driver into the classes folder. But then… 💥 Error: Class not found (H2 driver) I got stuck. 🤔 What was missing? After digging around, I realized something important: 👉 The H2 driver was not declared in classpath.txt And surprisingly… this step wasn’t mentioned in the documentation. 📌 So, what is classpath.txt? In simple terms: 👉 classpath.txt is a file that tells Java where to find your classes and external libraries when the application runs. Think of it like a “map” 📍 If a library (like H2) is not listed there, Java simply cannot see it, even if the file physically exists in your project. ⚠️ Why copying files isn’t enough I assumed that copying the .jar into the classes folder would be enough. But Java doesn’t automatically scan everything in that folder. 👉 If it’s not in the classpath → it doesn’t exist (from Java’s perspective) ✅ The fix Once I added the H2 driver path into classpath.txt, everything worked immediately. 💡 Key takeaways If you import an external library without declaring it in pom.xml, make sure it is also added to classpath.txt so the compiler and runtime can detect it If you declare dependencies properly in pom.xml, Maven will handle the classpath for you — no need to manually add them to classpath.txt When you see a “Class not found” error, always double-check how your dependencies are being included 🚀 What I learned This bug helped me truly understand: How Java loads dependencies at runtime The role of classpath.txt in builds The right way to include external libraries Sometimes, the smallest files teach the biggest lessons. If you’ve ever been stuck on a “Class not found” error, you know the pain 😅 Hope this saves someone a few hours (or days). #Java #Maven #Debugging #SoftwareEngineering #Learning
To view or add a comment, sign in
-
🌱 Common Spring Beginner Mistakes🚀 Common Spring Beginner Mistakes (and How to Avoid Them) When starting with Spring, these mistakes are very common 👇 ❌ 1. Using 'new' Instead of Dependency Injection Car car = new Car(); ❌ ✔ Always let Spring manage objects using DI ❌ 2. Not Understanding IoC & DI Clearly Writing code without knowing who creates objects Leads to confusion and poor design 📌 Learn IoC & DI before moving ahead ❌ 3. Using @Component Everywhere @Service → business logic @Repository → database layer @Controller → request handling ✔ Use the right annotation for the right layer ❌ 4. Mixing Controller, Service & Repository Logic @Controller class UserController { // DB logic here ❌ } ✔ Follow layered architecture ❌ 5. Field Injection Everywhere @Autowired private Service service; ❌ ✔ Prefer Constructor Injection ❌ 6. Ignoring Bean Lifecycle Not using @PostConstruct Not closing resources properly ✔ Understand create → use → destroy ❌ 7. Not Reading Error Messages Spring errors look big but are very informative Stack traces help you learn faster #Spring #SpringBoot #Java #LearningInPublic #BackendDevelopment #JavaDeveloper
To view or add a comment, sign in
-
The classic Spring Boot validation trap: you have a User DTO. On create, id must be null. On update, id must be present. So you either duplicate the DTO or add conditional checks that progressively make the codebase harder to read. Validation Groups solve this cleanly. You define interface markers — OnCreate and OnUpdate — then annotate constraints with the appropriate group. @Null(groups = OnCreate.class) on id for creates. @NotNull(groups = OnUpdate.class) on id for updates. Same DTO, entirely different validation behaviour depending on which group you pass via Validated in the controller. The javax.validation spec has supported this for years, but it doesn't get discussed enough. Teams discover it after the fact, usually after spending two sprints maintaining parallel DTO hierarchies that drift out of sync. A few things worth knowing: • Default constraints (no group specified) only run when no groups are passed. Once you start using groups, be explicit everywhere. • Spring's Validated is what enables group selection — Valid doesn't support groups. • Validation Groups compose — you can pass multiple groups when needed. We've written a complete guide on Spring Boot input validation covering groups, custom validators, controller-level wiring, and the common mistakes teams make. 👉 https://lnkd.in/eypuK5b9 #SpringBoot #Java #SoftwareDevelopment #CleanCode #APIDesign
To view or add a comment, sign in
-
-
#Post5 So far in this series, we explored concepts like HashMap, ConcurrentHashMap, CAS, and volatile. Now let’s step back and understand the foundation. We will now start with Multithreading Fundamentals. How does our code actually run? What is a Process and Thread? From Code to Process When we write a Java program: Compilation: javac Test.java → generates bytecode Execution: java Test → starts the program At this point, the JVM starts a new process in the operating system. This process is responsible for executing our program. The OS allocates resources to this process such as: • Memory • CPU time • Threads What is a Process? A process is simply a running instance of a program. Each process has its own memory and resources allocated by the operating system. What is a Thread? A thread is the smallest unit of execution inside a process. When a process starts, it begins with one thread called the main thread. From there, we can create multiple threads to perform tasks concurrently. Multitasking vs Multithreading Multitasking: The operating system runs multiple processes at the same time. Multithreading: A single process runs multiple threads concurrently. In simple terms: Operating System → Multiple Processes (Multitasking) → Each Process contains multiple Threads (Multithreading) Example Think of a web application: • One thread handles user requests • Another thread processes data • Another thread sends responses This allows multiple tasks to run efficiently at the same time. Key takeaway Code execution flow: Code → JVM → Process → Threads Understanding this flow is important because all advanced concepts like synchronization, CAS, and concurrent data structures are built on top of threads. In the next post, we’ll explore what happens inside a process (heap, stack, memory structure). #Java #SoftwareEngineering #Multithreading #BackendDevelopment #Programming
To view or add a comment, sign in
-
🚀 Dependency Injection: The Heart of Spring Most developers write code where objects create their own dependencies. Spring flips this on its head — and that's what makes it powerful. Dependency Injection (DI) means an object receives its dependencies from the outside instead of creating them itself. The IoC (Inversion of Control) container manages object creation, wiring, and lifecycle. // ❌ Without DI — tight coupling public class OrderService { private PaymentService payment = new PaymentService(); // hard-coded! } // ✅ With DI — loose coupling @Service public class OrderService { private final PaymentService paymentService; public OrderService(PaymentService paymentService) { this.paymentService = paymentService; // injected by Spring } } Why does this matter? ✔ Testability — swap real dependencies with mocks ✔ Flexibility — change implementations without touching consumers ✔ Single Responsibility — objects focus on their job, not wiring ✔ Less boilerplate — Spring handles object lifecycle Spring's ApplicationContext is the IoC container. It scans your classes, creates beans, resolves dependencies, and injects them automatically. You declare what you need; Spring figures out how to provide it. This is the concept everything in Spring Boot builds upon. Master this, and the rest clicks into place. #Java #SpringBoot #BackendDevelopment #DependencyInjection #IoC #SoftwareEngineering
To view or add a comment, sign in
-
💡 Understanding Collection-Based Dependency Injection in Spring When we talk about Dependency Injection (DI) in Spring, most of us think about injecting a single object. But did you know you can inject multiple beans at once using collections? 🤔 Let’s break it down in a simple way 👇 🔹 What is Collection-Based DI? Instead of injecting one object, Spring can inject a list, set, or map of beans into your class. 👉 This is useful when you have multiple implementations of the same interface. 🔹 What’s Happening Here? ✅ Spring scans all beans of type PaymentService ✅ It collects them into a List ✅ Injects them automatically into PaymentProcessor 🔹 Other Supported Collections You can also use: ✔ List<Interface> ✔ Set<Interface> ✔ Map<String, Interface> → Key = bean name Example: Map<String, PaymentService> paymentMap; 🔹 Why is this Useful? ✔ Helps implement strategy pattern easily ✔ Avoids manual bean selection ✔ Makes code more flexible & scalable 🔹 Pro Tip 🚀 Spring injects collections in a specific order if you use @Order or @Priority. 🔚 Summary Collection-based DI = Inject multiple beans → Handle dynamically → Write cleaner code If you're learning Spring deeply, this concept is a game changer when building scalable systems 🔥 #Java #SpringBoot #DependencyInjection #BackendDevelopment #CleanCode
To view or add a comment, sign in
-
Explore related topics
- Tips for Exception Handling in Software Development
- Best Practices for Exception Handling
- Advanced Debugging Techniques for Senior Developers
- How to Add Code Cleanup to Development Workflow
- Best Practices for Handling Software Edge Cases
- How to Write Clean, Error-Free Code
- How to Improve Your Code Review Process
- Preventing Bad Coding Practices in Teams
- How to Stabilize Fragile Codebases
- How To Prioritize Clean Code In Projects
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