In Java, how to convert Unchecked Exception into Checked Exception and Vice Versa in Java.
4 Answers
You can't convert. Rather you have to wrap into a new exception of the required type e.g. to convert to unchecked:
throw new RuntimeException(checkedException);
or to checked:
throw new Exception(uncheckedException);
(you may want to choose more meaningful/specific exception types)
 
    
    - 268,207
- 37
- 334
- 440
- 
                    Nice one, what if `checkedException` is `null`? What happens? – Unihedron Jul 25 '14 at 10:10
- 
                    1when you're "converting" a checkedException, it's probably not null. Otherwise it would be NullpointerException, unchecked. Problem solved ;) (ducks) – Olaf Kock Jul 25 '14 at 10:12
- 
                    1If you catch an exception, it won't be null. I'm assuming the above would be used in a catch() clause – Brian Agnew Jul 25 '14 at 10:16
Unchecked Exceptions are subclasses of RuntimeException, checked ones are not. So to convert one exception you'd have to change its inheritance, then fix the compiler errors because your new checked exception was never declared or caught.
 
    
    - 46,930
- 8
- 59
- 90
There is no way you can convert them. They are for different purposes. Caller needs to handle checked exceptions, while unchecked or runtime exceptions aren't usually taken care explicitly.
 
    
    - 8,201
- 4
- 38
- 57
Let's say you've got two exception classes ExceptionA and ExceptionB; and one of them is checked and the other is unchecked.  You want to convert ExceptionA to ExceptionB.
Assuming ExceptionB has a constructor like
public ExceptionB(Exception e) {
    super(e);
}
you can do something like
catch (ExceptionA e) {
    throw new ExceptionB(e);
}
to wrap objects of one exception class in the other.
 
    
    - 77,785
- 15
- 98
- 110
