Reputation: 1049
I just started to learn java. I'm trying to learn how Exception Handling works so i made up a little program:
public class Car {
protected String type;
protected String[] colors;
protected boolean isAvaiable;
public Car(String type, Collection<String> colors, boolean isAvaiable) throws NoColorException {
if (colors == null || colors.isEmpty()) {
throw new NoColorException("No colours!");
} else {
this.type = type;
this.colors = (String[]) colors.toArray();
this.isAvaiable = isAvaiable;
}
}
public static void main(String[] args) {
try {
Car n = new Car("asd", new ArrayList(), true);
} catch (NoColorException ex) {
}
}
}
This is my Exception class:
public class NoColorException extends Exception {
public NoColorException(String string) {
super(string);
}
}
The above code should throw an exception when i try to create the object but instead it runs.
Why does this happening?
Any help is greatly appreciated.
Upvotes: 1
Views: 85
Reputation: 874
It runs clearly because you are catching the Exception thrown in your Empty catch as said by @Eran and @Jens.
In order to see the Text in Red colors ; that is to throw the exception and visualize the Exception flow, Just make this change :
public static void main(String[] args) throws NoColorException {
Car n = new Car("asd", new ArrayList(), true);
}
Upvotes: -1
Reputation: 69440
You catch the exception and do nothing if the exception is catched:
Change:
try {
Car n = new Car("asd", new ArrayList(), true);
} catch (NoColorException ex) {
}
To:
try {
Car n = new Car("asd", new ArrayList(), true);
} catch (NoColorException ex) {
System.out.println(ex.getMessage())
}
and you will see the exception.
Note: Neven Catch an exception without logging it.
Upvotes: 4
Reputation: 393771
Your code throws an exception, which you catch in your empty catch block :
catch (NoColorException ex) {
}
Upvotes: 6