Need advice in throwing Exception in Java method - java

I am writing a method, in this I need to check that all the parameters I am receiving are not null. If any parameter is null, I need to print that custom message in as Exception.
My code look like this:
public void checkParam(String emp,String id,String addr)
{
try{
if(emp == null)
throw new Exception("Error: Missing emp");
else if(id== null)
throw new Exception("Error: Missing id");
else if(addr== null)
throw new Exception("Error: Missing addr");
}
catch (Exception e) {
e.printStackTrace();
return;
}
//if no exception
//do some action on params
}
My question is:
The above procedure is proper way for my requirement?
New Exception -- does it create lots of memory, is there any other way to simply doing this?

You can write this function as follows however you need to catch the exception where you will call this function.
public void checkParam(String emp,String id,String addr) throws Exception
{
if(emp == null){
throw new Exception("Error: Missing emp");}
else if(id== null){
throw new Exception("Error: Missing id");}
else if(addr== null){
throw new Exception("Error: Missing addr");}
//if no exception write some more code
//do some action on params
}
and when you will call this function do as follows
try {//pass valuse
checkParam(emp,id,addr)
}
catch(Exception exc) {
System.out.println(exc.getMessage());
}
also visit
http://www.javamex.com/tutorials/exceptions/exceptions_throwing.shtml
http://www.akadia.com/services/java_exceptions.html
http://www.functionx.com/java/Lesson15.htm

In your code, you are catching the exceptions yourself. So in case any of the parameters is null, the caller will not know of any error that has happened in your method.
You should instead throw the exception from your code in case of invalid parameter being passed
public void checkParam(String emp,String id,String addr) throws IllegalArgumentException{
//check for exceptions
//your code after throwing the exceptions
}
Also, instead of just throwing Exception, use specific type of exception to exactly indicate the cause of error like IllegalArgumentException in this case

You are catching the exception that you created, which in this case, nothing will happen. To throw the exception out:
public void checkParam(String emp, String id, String addr) throws Exception {
if(emp == null)
throw new Exception("Error: Missing emp");
if(id == null)
throw new Exception("Error: Missing id");
if(addr == null)
throw new Exception("Error: Missing addr");
}
This may crash the app if you do not catch the error outside of this function.
Or, if you just wanna make sure the params are there without crashing, just return a boolean.
public boolean checkParam(String emp, String id, String addr) {
return emp != null && id != null && addr != null;
}
Even better, if you do not need to know which variable is actually missing, just create a function which accepts different amount of params:
public boolean checkParam(String... param) {
if(param != null) {
int size = param.length;
for(int i = 0; i < size; i++) {
if(param[i] == null)
return false;
}
return true;
} else {
return false;
}
}

public void checkParam(String emp,String id,String addr)
{
if(emp == null || id == null || addr == null) {
// the conditional operator checking has same behavior
// as your if - else, to find, which parameter is null
// it report first ever parameter which is null
throw new Exception("Error: Missing "+ emp == null ? "emp" : id == null ?
"id" : add == null ? "addr" : "" );
}
// control will reach here if no exception occured
}

Related

Write own exception in logger

Have method for insert elements in array.
public boolean insertElementToSlot(Element element, int index) {
checkArray(index);
try {
if (element != null && mas[index] == null) {
mas[index] = element;
return true;
} else {
throw new ElementValidationException("Element.insertElementToSlot", device);
}
} catch (ElementValidationException d) {
logger.log(Level.SEVERE, ""+d);
}
return false;
}
And own exception class with method:
public ElementValidationException(String operation, Element element) {
super("Element is not valid for operation" + checkOperation(operation));
this.element = element;
}
When testing method insertElementToSlot, I have error
java.lang.AssertionError: Expected exception: com.inventory.exception.ElementValidationException
Why is the error related and how to solve it?
If you have a unit test which expects an exception, it has to be thrown out of the test. It doesn't check that this exception is thrown anywhere in the code but caught.
NOTE: your exception isn't being used as an exception and could be replaced with a log message
Your code is basically the same as
public boolean insertElementToSlot(Element element, int index) {
checkArray(index);
if (element != null && mas[index] == null) {
mas[index] = element;
return true;
}
logger.log(Level.SEVERE, "some.package.ElementValidationException");
return false;
}

Trouble with unhandled exceptions

I have two methods. Method A calls method B. I cannot change the exceptions of neither (homework demands). However, the 2 exceptions mean the exact same thing, so when I call method B on A, I already know that B's exception is not getting thrown. However, I still get the "unhandled exception" error from Eclipse. How can I avoid it?
Here are the methods
public void createProfile(Profile user) throws PEException {
Vector<Profile> p = new Vector<Perfil>();
try{
if (repository.search(user.getUsername()) == null) {
repository.register(user); //error on this line when I call the method on main
}
else {
throw new PEException(user.getUsername());
}
} catch (PEException e){
e.printStackTrace();
}
}
public void register(Profile user) throws UJCException {
try {
if (this.search(user.getUsername()) == null) {
this.users.add(user);
}
else {
throw new UJCException(user.getUsername());
}
} catch (UJCException e) {
e.printStackTrace();
}
}
I MUST NOT change the definitions of the methods (I can't throw UJCException on createProfile). Thanks in advance
You shouldn't be throwing the exceptions and then catching them inside the same method. That defeats the purpose of throwing the exception in the first place. the methods which calls your 2 methods should expect nothing (void) or the exception in the event that something went wrong. Make sure your methods createProfile() and register() can actually throw their exception so methods calling them can catch the exception and do whatever it is they need to when the exception is thrown.
public void createProfile(Profile user) throws PEException {
Vector<Profile> p = new Vector<Perfil>(); //not being used...
if (repository.search(user.getUsername()) == null) {
try{
repository.register(user);
}catch(UJCException e){
e.printStackTrace();
throw new PEException(user.getUsername());
}
}
else {
throw new PEException(user.getUsername());
}
}
public void register(Profile user) throws UJCException
{
if (this.search(user.getUsername()) == null) {
this.users.add(user);
}
else {
throw new UJCException(user.getUsername());
}
}
Now when you call these methods wrap the call in a try catch and catch the appropriate exception depending on which method was called

ArrayList IndexOutOfBoundsException even though handled

I have a method which tries to get the current message in an arraylist of mesages and if there are none then it returns null, however I get an index out of bounds exception and I can't understand why
public Message getCurrent() {
if(this.size() <= 0) {
return null;
}else {
return this.get(currentMessageIndex);
}
}
The following calls the above method in another class and throws the exception:
public void run() {
while (running) {
//Message msg = clientQueue.getLast(); // Matches EEEEE in ServerReceiver
Message msg = clientQueue.getCurrent();
System.out.flush();
if (msg != null) {
if (msg.getSent() == false) {
client.println(msg);// Matches FFFFF in ClientReceiver
client.flush();
msg.setSent();
}
}
}
return;
}
public Message getCurrent() {
if(this.size() <= 0) {
return null;
}else {
return (this.size() > currentMessageIndex) ? this.get(currentMessageIndex) : null;
}}
Can you try with this, I have handled fail over case.
Just use
this.size()-1
Instead of
this.size()

Handling ConstraintviolationException in JPA

My problem is very usual but i can't seem to find any solution. I have searched a lot but didn't find anything
Situation:
tried to insert a row which caused foreign key violation that caused my transaction to rollback.
No matter what exception i handle it always throws 500 from my rest endpoint which is not acceptable at all
Question:
How to handle this gracefully. Below is my code which is not working
#Transactional(dontRollbackOn={InvalidModelException.class,PersistenceException.class,ConstraintViolationException.class,MySQLIntegrityConstraintViolationException.class})
#Override
public PointAudit createPointAudit(PointAudit pointAudit) throws EmptyModelException, InvalidModelException {
if(pointAudit != null) {
try {
this.entityManager.persist(pointAudit);
this.entityManager.flush();
}
catch(RollbackException x) {
LOGGER.error(x.getMessage(), x);
}
catch(PersistenceException x) {
if(x.getCause() instanceof ConstraintViolationException) {
if(x.getCause().getCause() instanceof MySQLIntegrityConstraintViolationException)
{
MySQLIntegrityConstraintViolationException e = (MySQLIntegrityConstraintViolationException)x.getCause().getCause();
if(e.getMessage().contains("USER_ID")) {
throw new InvalidModelException("Invalid user is provided");
}
else {
if(e.getMessage().contains("STATUS")) {
throw new InvalidModelException("Invalid status is provided");
}
else {
if(e.getMessage().contains("CHANNEL")) {
throw new InvalidModelException("Invalid channel is provided");
}
else {
if(e.getMessage().contains("ACTION")) {
throw new InvalidModelException("Invalid action is provided");
}
}
}
}
}
}
else {
while( !(x.getCause() instanceof RollbackException) || x.getCause() == null) {
LOGGER.error(x.getMessage(), x);
}
}
}
}
else {
throw new EmptyModelException("Point Audit is empty");
}
return pointAudit;
}
If any further code is required please let me know

Catch empty String. Which exception to use?

As the title suggests I am trying to catch an empty String. I have a class (the class of the object I am trying to create) that throws an Exception when the String is null or empty (check with str.isEmpty).
When I try to create the object with an empty String in another class it works as intended and throws an Exception. However, I want this class to Catch that Exception and notify the user. But it never seems to Catch the Exception, even if I try to write Catch(Exception exc).
Now I know a null or empty String is not illegal. But my intention was that the object class was supposed to make it so. Instead it seems as if the catch block doesn't care at all. I am starting to think that I would have to create my own exception class of some sort... or is there something I am missing? Here are the relevant parts of the code:
The object class constructor:
public Valueables(String name){
//name.trim().length() == 0
if(name == null || name.isEmpty()){
try {
throw new Exception("Subclasses of Valueables cannot take in an empty String or null value for the \"name\" constructor");
} catch (Exception e) {
e.printStackTrace();
System.exit(2);
}
}
else
this.name = name;
}
The other class (the new Trinket object is a subclass of Valueables. The one with the constructor code above):
while(loopPassErrorControl == false){
//I don't think the try loop is relevant. But just to make sure...
//Otherwise just ignore it
try{
TrinketForm Tform = new TrinketForm();
answer = JOptionPane.showOptionDialog(ValueablesFrame.this, Tform, "Nytt smycke", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options , null);
if (answer != JOptionPane.OK_OPTION){
return;
}
valueablesList.add(new Trinket(Tform.getName(), Tform.getGemstones(), Tform.getMetalSelected()));
loopPassErrorControl = true;
}catch(NumberFormatException | NullPointerException exc) {
JOptionPane.showMessageDialog(ValueablesFrame.this, "NĂ¥got gick fel");
}
}
//Test
for(Valueables obj : valueablesList){
System.out.println(valueablesList);
}
First throw a RuntimeException on Valuable:
public Valueables(String name){
//name.trim().length() == 0
if(name == null || name.isEmpty()){
throw new RuntimeException("Subclasses of Valueables cannot take in an empty String or null value for the \"name\" constructor");
}
else
this.name = name;
}
And do not catch the exception.
Second, on the other class catch a RuntimeException and show a mesage:
...}catch(RuntimeException exc) {
JOptionPane.showMessageDialog(exc.getMessage());
}
Hope helped you!
Already made a question about empty strings, an empty string is still not null so it must throw "IllegalArgumentException" if you WANT to catch it.
try to catch it as the generic Exception, replace the NuumberFormatException and NullpointerException.
You can also do this in Java.
try {
//Some Code here
} catch (NumberFormatException | NullPointerException ex) {
//Handle NumberFormat and NullPointer exceptions here
} catch (Exception ex) {
//Handle generic exception here
}

Categories

Resources