Java Programming
Java Programming
June 14, 2025 at 01:05 PM
*⚠️ Exception Handling in Java* *1️⃣ What is an Exception?* An exception is an unwanted event that disrupts normal program flow. Example: Dividing a number by zero. *2️⃣ Types of Exceptions* - *Checked Exceptions:* Must be handled (e.g., IOException, SQLException) - *Unchecked Exceptions:* Occur at runtime (e.g., NullPointerException, ArithmeticException) *3️⃣ try-catch Block* Used to handle exceptions safely. ```java try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero!"); } ``` *4️⃣ finally Block* Always runs, even if exception occurs. Used for closing resources. ```java finally { System.out.println("This always executes."); } ``` *5️⃣ throw Keyword* Used to *manually* throw an exception. ```java throw new IllegalArgumentException("Invalid input"); ``` *6️⃣ throws Keyword* Used in method signature to declare exceptions. ```java void readFile() throws IOException { // code that might throw exception } ``` *7️⃣ Custom Exception* You can create your own exception class: ```java class MyException extends Exception { MyException(String msg) { super(msg); } } ``` *8️⃣ Best Practices* - Catch specific exceptions (not just Exception) - Don’t suppress exceptions silently - Clean up with `finally` or try-with-resources - Always log the exception (e.g., `e.printStackTrace()`) Java Roadmap: https://whatsapp.com/channel/0029VamdH5mHAdNMHMSBwg1s/810 *React ❤️ for more*
❤️ 👍 😮 🙏 😂 👏 💀 🗿 65

Comments