Java Exception Handling Keywords: try, catch, finally, throw, throws

🚀 Day 21 | Core Java Learning Journey 📌 Topic: Exception Handling Keywords in Java Today I learned the most important Java exception handling keywords: try, catch, finally, throw, throws — and the commonly confused finalize(). Understanding them is essential for writing clean, production-ready Java code 💡 🔹 try ✔ Wraps risky code ✔ Must be followed by catch or finally ✔ Cannot exist alone ✔ Multiple catch blocks allowed Syntax : try { // risky code } catch(Exception e) { // handling } 🔹 catch ✔ Handles exceptions from try ✔ Takes exception object as parameter ✔ Order matters (Child → Parent) ✔ Multiple catch blocks allowed 🔹 finally ✔ Always executes (whether exception occurs or not) ✔ Executes even if return statement is present ✔ Used for cleanup (files, DB, etc.) ✔ Won’t execute only if JVM crashes or System.exit() is called 🔹 throw ✔ Explicitly throws an exception ✔ Used inside method body ✔ Can throw checked & unchecked exceptions ✔ Followed by exception object throw new IllegalArgumentException("Invalid Age"); 🔹 throws ✔ Declares exception responsibility ✔ Used in method signature ✔ Mainly for checked exceptions ✔ Can declare multiple exceptions public void readFile() throws IOException { // code } 🔥 throw vs throws ✔ throw → Inside method body ✔ throws → In method declaration ✔ throw → Single exception ✔ throws → Multiple exceptions 🔹 finalize() (Important) ✔ NOT part of exception handling ✔ Belongs to Garbage Collection ✔ Defined in Object class ✔ Called before object destruction ✔ Deprecated (Java 9+) 🔥 finally vs finalize() ✔ finally → Exception handling block ✔ finalize() → GC method ✔ finally → (Almost) always runs ✔ finalize() → May or may not run 📌 Key Takeaways ✔ finally ensures cleanup ✔ throw creates exceptions ✔ throws delegates responsibility ✔ finalize() relates to memory management Small keywords — powerful concepts 💻🚀 Special thanks to Vaibhav Barde Sir . #CoreJava #JavaLearning #ExceptionHandling #JavaDeveloper #OOP #LearningJourney

  • graphical user interface, application, email

To view or add a comment, sign in

Explore content categories