I'm trying to learn java and I have a little problem with understanding how exceptions work.
When do we need to use throw after a condition? As an example
public Ex(String name, String prenom, int age) throws exceptionex { if (name.length() < 3 && prenom.length() < 3 && age < 1) throw new exceptionex(); this.age = age; this.name = name; this.prenom = prenom; } excepetionex is an empty class which extends Exception.
And what is the difference between the previous example and this one?
public Ex(String name, String prenom, int age) { if (name.length() < 3 && prenom.length() < 3 && age < 1) try { throw new exceptionex(); } catch (exceptionex e) { e.printStackTrace(); } this.age = age; this.name = name; this.prenom = prenom; } And what does printstackTrace exactly do?
Do we always need to create another class if we wanted to customise an exception (exeptionex here ) or we can just use (throw new Exception)?
I googled my questions but i didn't find an answer which i can understand maybe because I'm new or because English is not my native language I need a simple explanation as much as possible please.
new exceptionex().printStackTrace()does much the same.Ex; the second one prints something to stderr, and then creates the object anyway.printstackTraceexactly do?" Learn to read the docs, that's where most of your answers are.