Trying to create custom exception am extending the Exception class, which is resulting in the error
error: Exception is already defined in this compilation unit
If you remove the import statement --> import java.lang.Exception
then new set of errors is coming below
--------------------Configuration: --------------------
E:\ArjunJava\Exception.java:29: error: incompatible types: MyException cannot be converted to Throwable
throw new MyException("Array size is less than what you are referencing");
^
E:\ArjunJava\Exception.java:35: error: incompatible types: MyException cannot be converted to Throwable
catch(MyException me)
^
E:\ArjunJava\Exception.java:37: error: cannot find symbol
System.out.println("Exception caught "+me.getMessage());
symbol: method getMessage() location: variable me of type MyException
E:\ArjunJava\Exception.java:15: error: constructor Exception in class Exception cannot be applied to given types;
super(message);
^
required: no arguments
found: String
reason: actual and formal argument lists differ in length
4 errors
Process completed.
import java.lang.Exception;
class MyException extends Exception {
MyException(String message) {
super(message);
}
}
public class Exception {
public static void main (String[] args) {
// array of size 4.
int[] arr = new int[4];//Referring 5th Element
try {
int i = arr[4]; // this statement causes an exception
throw new MyException("Referring to element more than Array size");
}
catch(MyException me) {
System.out.println("Exception caught : "+me.getMessage());
}
}
}
Output:
Exception caught : Referring to element more than Array size