why cant custom Exception be caught in generic catch clause - java

Please examine my custom exception below:
public class ReportException extends Exception {
private int mCode = -1;
private String mString = "";
public ReportException(int code, String description)
{
super(description);
mCode = code;
mString = description;
}
public int getCode()
{
return mCode;
}
public String getString()
{
return mString;
}
}
My question is why is this illegal in another class:
try{
throw new NullPointerException();
}
catch(ReportException e){
}
To me a NullPointerException is derived from Exception class and so is my custom ReportException so since there the same type i'd expect it can be caught in the catch clause. But my IDE says this is illegal. I had this discussion with a colleague of mine and he said there it cant be done but im just wondering why since they both derive from the same Exception class. This looks to defy polymorphism.

A NullPointerException and your ReportException are both Exceptions, but to catch a ReportException, you must throw a ReportException (or a subclass). A NullPointerException is not a subclass of ReportException, so it's not caught.
Throw a ReportException instead.

Some code inside the try block has to throw your checked exception before you can explicitly catch it.
This is valid:
try {
throw new ReportException();
}
catch(ReportException e){
// handle it
}
See Java: checked vs unchecked exception explanation

Every single class in java is a successor of java.lang.Object, but that doesn't mean that all of these classes are cast-able to each-other.
To a computer those two classes are completely different to each-other.

Related

What is type of exception to throw if property is not injected?

If module was not injected, in methodA which type of exception can i throw?
public class Customer{
private String module;
public void methodA(){
if (StringUtils.isBlank(module))
throw new ???
}
}
You can either create your own custom exception, or throw IllegalStateException along with an appropriate message. From the docs:
Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation. (emphasis mine)
Since you don't expect module to be blank, you're in an invalid state and hence this exception would be appropriate to throw in this case IMO.
No Specfic predefined Exception is already there which you can make use of. So you can make a new one like ModuleException:-
public class ModuleException extends Exception {
public ModuleException() { super(); }
public ModuleException(String message) { super(message); }
public ModuleException(String message, Throwable cause) { super(message, cause); }
public ModuleException(Throwable cause) { super(cause); }
}
After creating ModuleException you can throw it in your class like:-
public void methodA(){
if (StringUtils.isBlank(module))
throw new ModuleException("Module is blank but is MANDATORY");
}
I would've said to use NullPointerException but the isBlank method also returns true when it's an empty String. The best option would probably be to make your own Exception (info can be found here). That way you also get complete customization.

High Level Overview Of Throwing Exceptions In Java

I am a little bit confused with exceptions in Java and when to use which particular style of implementation.
I used IllegalArgumentException as an example, but the main point I would like to address is when does one throw, extends or throw new exception?
Also as an additional point I have an assignment where I have to create a java class and the spec vaguely states that the constructor should throw an IllegalArgumentException so which one would be the best to use?
public class Test{
//when does one use this type of exception
public Test(String yourName) throws IllegalArgumentException{
//code implemented
}
//when does one use this type of exception
public Test(String yourName) extends IllegalArgumentException{
//code implemented
}
public Test(String yourName){
if(yourName.length() <= 0){
//why not use this type of exception instead
//and what happens when I use this type of exception
throw new IllegalArgumentException("Please Enter Your Name..!");
}
}
}
Thanks in advance.
When some Exception occurs, you have two ways of handling it: doing throws from the method or doing try-catch. The first one looks like this:
public class MyClass {
public void myMethod() throws IllegalArgumentException {
someOtherMethod();
}
}
In this case you know that someOtherMethod() can throw an exception and you don't want to handle it - you just pass it further. After that, the invoker of myMethod() should take care of the Exception.
But the second way is when you handle it by yourself:
public void myMethod() {
try {
someOtherMethod();
} catch (Exception e) {
System.out.println("You've got an exception!");
}
}
About throwing exceptions manually - you may suppose that you do it in someOtherMethod(). When you do throw new IllegalArgumentException("Please Enter Your Name..!"); the program stops with a message about this exception (unless you handle it in a try-catch way).
And at last, you extend some exception, when you create your own Exception class:
class MyException extends IllegalArgumentException {
...
}
In this case you may do throw new MyException(); in your code.
I'd advise you to read more about exceptions in Java to understand what is going on. You may start with this lesson.
To ensure that you don't end up creating exceptions which already have equivalent in the standard library, I normally have a peek at the documentation before creating new exceptions. Also, it's very easy to go crazy with really big exception hierarchies if you are not careful. Don't create new exceptions just because you think you need to throw one somehow; create one because a code somewhere down the call stack would be doing something useful/different with that exception.
public Test(String yourName) throws IllegalArgumentException
You normally never specify runtime exception in the throws clause though it might be helpful if you need this information to be part of the public API.
public Test(String yourName) extends IllegalArgumentException
This doesn't look right and isn't valid Java.
I would only create a new exception type when you need to. You need a new type when you expect the caller to have catch clause for your new exception.
you can create new exceptions just to be more descriptive but that is what I use the message for.

Throwing exceptions and catching them elsewhere

I was wondering if it was possible to write a method to throw an exception and have another method catch these exceptions.
For example,
public static void checkCircle() {
try {
checkPixel(a);
checkPixel(b);
checkPixel(c);
} catch (MyException e) {
System.out.println("not circle");
}
private static void checkPixel(anything) {
if (img.getRGB(xValue, yValue) != pOrigColour) {
throw new MyException();
}
}
class MyException extends Exception {
public MyException() {
}
public MyException(String msg) {
super(msg);
}
}
Thing is I want to the checkPixel method to throw a MyException, indicating that there is no circle, regardless of the results of the other calls.
Yes, it is possible. In your method declaration, you can add a throws clause, which indicates that your method might throw an exception.
In your case, you should modify your method declaration like this:
private static void checkPixel(anything) throws MyException {
// ...
}
You should note that exceptions should be used for... exceptional situations. Using them for simple error handling is highly unconventional, and adds unnecessary burden on users of your classes. In your case, you might want to add a boolean hasCircleAtLocation () method that would return true if there is a circle at the provided location.

Using throw for user defined exception

Following is the code where " throw use; " shows an error.Why? How to use throw for user defined exceptions?Give some example?
class use extends Exception{
public String toString() {
return "too many exceptions";
}
}
class user{
public static void main(String s[]) {
int i=3;
try {
if(i>1)
throw use;
}
catch(use e) {
System.out.println(e.toString());
}
finally{
System.out.println("program executed successfully!");
}
}
}
you need an instance of the exception class to throw it:
throw new use();
or
use a = new use();
throw a;
In the future please follow Java naming conventions, it will make your code much more readable. (class names should start with a capital letter).
User defined exceptions can be created and thrown in Java.
By inheriting the Exception class you can create your own exceptions.
And it can be thrown as and when required
Following example shows how to create and throw user defined exceptions
http://www.csnotes32.com/2014/09/how-to-create-user-defined-exception-in.html
And remember, you don't need to roll your own.
throw new RuntimeException("Do not instantiate this class");
(old question, but I always forget syntax, so stashing on google)

How to create a custom exception type in Java? [duplicate]

This question already has answers here:
How can I write custom Exceptions?
(5 answers)
Closed 3 years ago.
I would like to create a custom exception in Java, how do I do it?
...
try{
...
String word=reader.readLine();
if(word.contains(" "))
/*create custom exception*/
}
catch(){
When I create my custom exception with throw new..., I obtain the error unreported exception...must be caught or declared to be thrown
You should be able to create a custom exception class that extends the Exception class, for example:
class WordContainsException extends Exception
{
// Parameterless Constructor
public WordContainsException() {}
// Constructor that accepts a message
public WordContainsException(String message)
{
super(message);
}
}
Usage:
try
{
if(word.contains(" "))
{
throw new WordContainsException();
}
}
catch(WordContainsException ex)
{
// Process message however you would like
}
You need to create a class that extends from Exception. It should look like this:
public class MyOwnException extends Exception {
public MyOwnException () {
}
public MyOwnException (String message) {
super (message);
}
public MyOwnException (Throwable cause) {
super (cause);
}
public MyOwnException (String message, Throwable cause) {
super (message, cause);
}
}
Your question does not specify if this new exception should be checked or unchecked.
As you can see here, the two types are different:
Checked exceptions are meant to flag a problematic situation that should be handled by the developer who calls your method. It should be possible to recover from such an exception. A good example of this is a FileNotFoundException. Those exceptions are subclasses of Exception.
Unchecked exceptions are meant to represent a bug in your code, an unexpected situation that you might not be able to recover from. A NullPointerException is a classical example. Those exceptions are subclasses of RuntimeException
Checked exception must be handled by the calling method, either by catching it and acting accordingly, or by throwing it to the calling method. Unchecked exceptions are not meant to be caught, even though it is possible to do so.
Great answers about creating custom exception classes. If you intend to reuse the exception in question then I would follow their answers/advice. However, If you only need a quick exception thrown with a message then you can use the base exception class on the spot
String word=reader.readLine();
if(word.contains(" "))
/*create custom exeception*/
throw new Exception("My one time exception with some message!");
}
As a careful programmer will often throw an exception for a special occurrence, it worth mentioning some general purpose exceptions like IllegalArgumentException and IllegalStateException and UnsupportedOperationException. IllegalArgumentException is my favorite:
throw new IllegalArgumentException("Word contains blank: " + word);
Since you can just create and throw exceptions it could be as easy as
if ( word.contains(" ") )
{
throw new RuntimeException ( "Word contains one or more spaces" ) ;
}
If you would like to be more formal, you can create an Exception class
class SpaceyWordException extends RuntimeException
{
}
Either way, if you use RuntimeException, your new Exception will be unchecked.
An exception is a class like any other class, except that it extends from Exception. So if you create your own class
public class MyCustomException extends Exception
you can throw such an instance with
throw new MyCustomException( ... );
//using whatever constructor params you decide to use
And this might be an interesting read
You just need to create a class which extends Exception (for a checked exception) or any subclass of Exception, or RuntimeException (for a runtime exception) or any subclass of RuntimeException.
Then, in your code, just use
if (word.contains(" "))
throw new MyException("some message");
}
Read the Java tutorial. This is basic stuff that every Java developer should know: http://docs.oracle.com/javase/tutorial/essential/exceptions/
You have to define your exception elsewhere as a new class
public class YourCustomException extends Exception{
//Required inherited methods here
}
Then you can throw and catch YourCustomException as much as you'd like.
You can create you own exception by inheriting from java.lang.Exception
Here is an example that can help you do that.

Categories

Resources