In: Computer Science
JAVA
Write a program that demonstrates how various exceptions are caught with
catch (Exception exception)
This time, define classes ExceptionA (which inherits from class Exception) and ExceptionB (which inherits from class ExceptionA). In your program, create try blocks that throw exceptions of types ExceptionA, ExceptionB, NullPointerException and IOException. All exceptions should be caught with catch blocks specifying type Exception.
import java.io.IOException;
//Exception A class
class ExceptionA extends Exception {
private String msg;
public ExceptionA(String aMsg) {
super();
msg = aMsg;
}
@Override
public String toString() {
return msg;
}
}
// Exception B class
class ExceptionB extends ExceptionA {
public ExceptionB(String aMsg) {
super(aMsg);
}
@Override
public String toString() {
return super.toString();
}
}
public class ExceptionTest {
public static void main(String[] args) {
try {
// throwing
ExceptionA and catching it
throw new
ExceptionA("ExceptionA example..!!!");
} catch (ExceptionA e) {
System.out.println(e);
}
try {
// throwing
ExceptionB and catching it
throw new
ExceptionB("ExceptionB example..!!!");
} catch (ExceptionB e) {
System.out.println(e);
}
try {
// throwing
NullPointerException and catching it
throw new
NullPointerException("NullPointerException example..!!!");
} catch (NullPointerException e)
{
System.out.println(e);
}
try {
// throwing
IOException and catching it
throw new
IOException();
} catch (IOException e) {
System.out.println(e);
}
}
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me