I wrote a custom exception as:
public class CustomException extends Exception {
public CustomeException(String message) {
super(message);
}
}
and try some tests as:
public static String test(String string) throws CustomException {
if (string == null) {
throw new CustomException("Empty String");
}
return string;
}
public static void main(String[] args) throws CustomException {
String testException = test(null);
System.out.print(testException);
}
When I run, it throws the exception. I wonder how can it returns the exception object instead of throwing an exception.
I mean the testExpception
object will be CustomExpception
when we input the string as null. Can we do it ?
That's for the try catch is designed for.
public static void main(String[] args) {
try{
String testException = test(null);
}
catch(CustomException e){// object e can be used for analysing the exception
e.printStackTrace();
}
}
Plus there is a typo in you exception constructor.it should be CustomException
not CustomeException
and make the same change at other places as well
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.