Write own exception in logger - java

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;
}

Related

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

Dealing with exception in other method by using other method catch

I need to see the result as a boolean result: true. But there's a catch I need to do it in a non-ordinary way.
import java.io.IOException;
public class FlashLight {
private Bulb bulb;
private Battery[] batteries;
public void on() {
try {
if (this.IsThereEnoughPower()) {
this.bulb.setOn(true);
for (Battery b : batteries) {
b.setPower(b.getPower() - this.bulb.getBrightness());
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
this.setBatteries(new Battery[4]);
}
}
I need to catch the exception in method on() but i can only modify method: DetermineIfFlashlightCanBeTurnedOn
public boolean DetermineIfFlashlightCanBeTurnedOn() throws IOException {
return bulb != null && DetermineIfBatteriesAreInstalled() && IsThereEnoughPower();
}
private boolean DetermineIfBatteriesAreInstalled() throws IOException {
if (batteries.length < 4) {
throw new IOException(Math.abs(-4 + batteries.length));
}
for (Battery b : batteries) {
if (b == null) {
return false;
}
}
return true;
}
private boolean IsThereEnoughPower() {
for (Battery b : batteries) {
if (b.getPower() < MIN_BATTERY_POWER) {
return false;
}
}
return true;
}
private static void testLatarki(String... args) {
FlashLight flashlight = new Flashlight();
System.out.println(flashlight.DetermineIfFlashlightCanBeTurnedOn());
}
}
Exception can be caught only in on() method.
DetermineIfBatteriesAreInstalled() DetermineIfFlashlightCanBeTurnedOn
must be signed as: throws IOException.
You can use try{}catch(){} instead :
public boolean DetermineIfFlashlightCanBeTurnedOn() {
try {
return bulb != null && DetermineIfBatteriesAreInstalled() && IsThereEnoughPower();
} catch (Exception e) {
//log your exception
}
return false;
}
I forgot to tell you guys i can use try/catch blocks only in on()
method
In this case you can use RuntimeException you don't need to use throws IOException in your method:
if (batteries.length < 4) {
throw new RuntimeException(Math.abs(-4 + batteries.length)+"");
}
So :
public boolean DetermineIfFlashlightCanBeTurnedOn() {
//--not need to use throw throws IOException-------^
return bulb != null && DetermineIfBatteriesAreInstalled() && IsThereEnoughPower();
}
private boolean DetermineIfBatteriesAreInstalled() {
//--not need to use throw throws IOException------^
if (batteries.length < 4) {
throw new RuntimeException(Math.abs(-4 + batteries.length) + "");
//----------^^
}
for (Battery b : batteries) {
if (b == null) {
return false;
}
}
return true;
}
You can read more here Is there a way to throw an exception without adding the throws declaration?

In selenium with java need reusable method to verify isElement present which may have different locators like xpath, id, class name

I want to write a reusable method to identify whether the web Element is Present or not.
This method needs to accept e different locators like xpath, id, class name.
Here is the code snipped I tried, but not worked for the line.
if(Obj.isDisplayed())
public static boolean isElementPresent(WebDriver driver, WebElement Obj)
{
boolean result = false;
try
{
// if(Obj.isDisplayed())
if(driver.findElement(By.id("username")) != null)
{
System.out.println("WEBELEMENT Username FOUND");
result = true;
}
else
{
result = false;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
Below method returns true in case element present.
public boolean isElementPresent(WebDriver driver,By locator){
if(driver.findElements(locator).size()!=0){
//Element present
return true;
}
else{
//Element not present
return false;
}
}
Example:
isElementPresent(By.id("test"));
isElementPresent(By.xpath("//test1"));
For your case solution will be Try/Catch:
public boolean isElementPresent(WebElement element) {
try {
element.getText();
return true;
} catch (NoSuchElementException e) {
return false;
}
If element not exists on the page then element.getText() will throw NosuchElementException, method will catch this exception and returns false.
Try it and let me know if it works for you.

Need advice in throwing Exception in Java method

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
}

Categories

Resources