Handling Exceptions in Synchronized Blocks
This program demonstrates handling exceptions in synchronized blocks.
Problem Statement
Write a Java program that handles exceptions inside synchronized blocks.
Source Code
| 1 | class Shared { |
| 2 | synchronized void risky(){ |
| 3 | try { |
| 4 | int result=10/0; |
| 5 | } catch(Exception e) { |
| 6 | System.out.println("Eduinq Exception in Synchronized Block: "+e.getMessage()); |
| 7 | } |
| 8 | } |
| 9 | } |
| 10 | public class SynchronizationExceptionExample { |
| 11 | public static void main(String[] args) { |
| 12 | System.out.println("Eduinq Synchronization Exception Example"); |
| 13 | Shared s=new Shared(); |
| 14 | s.risky(); |
| 15 | } |
| 16 | } |
Program Output
Eduinq Synchronization Exception Example Eduinq Exception in Synchronized Block: / by zero
Explanation
Exceptions inside synchronized blocks must be handled to prevent lock issues. - Try-catch ensures thread safety and reliability. - Prevents program crash during concurrent execution. - In enterprise systems, synchronization exception handling ensures safe concurrency. Conclusion: Shows handling exceptions in synchronized blocks.