I am quite new to Java and I am struggeling to understand Exceptions.
In an Excercise I was supposed to implement the Interface "exceptions.excercise.Validator" in the class "ValidatorImpl" and the Method "User#validate".
I am struggeling to understand what exactly is happening in these lines of codes and I would really appreciate it, if somebody could help me :):
I am not sure if you need the whole java project to understand the code but here's what I don't really understand:
*In User.java
public void validate() throws UserException {
Validator valid = new ValidatorImpl();
try {
valid.validateAge(this.getAge());
valid.validateEmailWithRuntimeException(this.getEmail());
} catch (ValidationException e) {
throw new UserException("age is incorrect", e);
} catch(ValidationRuntimeException e ) {
throw new UserException("mail is incorrect", e);
}
}
In ValidatorImpl.java:
package exceptions.excercise;
public class ValidatorImpl implements Validator {
#Override
public void validateAge(int age) throws ValidationException {
if ((age < 0) || (age > 120)) {
throw new ValidationException(age + "not betweeon 0 and 120");
}
}
#Override
public void validateEmailWithRuntimeException(String email) {
if (email == null) {
throw new ValidationRuntimeException("email is null");
}
if (!email.contains("#")) {
throw new ValidationRuntimeException("email must contain #sign");
}
}
}
I know this is quite a lot.
Thank you if you read all of this :)
First, you have a try-catch block. This will catch exceptions thrown in the try-part and if an exception is found they'll run the catch-block for the type of exception. The methods valid.validateAge(int) and valid.validateEmailWithRuntimeException(String) both can throw exceptions.
If the age is under 0 or over 120 validateAge will throw an ValidationException. The try-catch will catch that and will run the first catch-block, which will output a new UserExeption("age is incorrect").
If the age is valid, validateEmailWithRuntimeException will be called next.
This works the same way! If the Email is invalid, a ValidationRuntimeException will be thrown and catched. In this case, the second catch-block will be called and a new UserExeption("mail is incorrect") will be outputted.
Related
#When("^user clicks linkedin button of the first news item$")
public void user_clicks_linkedin_button_of_the_first_news_item()
{
try
{
firstSocialShareElement = driver.findElement(By.className("social-share-linkedin"));
if(firstSocialShareElement!=null && firstSocialShareElement.isDisplayed())
{
firstSocialShareElement.click();
}
}
catch(NoSuchElementException e)
{
}
}
It turns out it was a simple case of class name conflict.
Since i didn't specify the full qualified name of the exception as org.openqa.selenium. NoSuchElementException
It was considering it to be java.util. NoSuchElementException
and hence the exception was not getting caught.
Now the problem is resolved.
try
{
firstSocialShareElement = driver.findElement(By.className("social-share-linkedin"));
if(firstSocialShareElement!=null && firstSocialShareElement.isDisplayed())
{
firstSocialShareElement.click();
}
}
catch(org.openqa.selenium. NoSuchElementException e)
{
}
I am using Simple XML in my project and have following problem
Source code
#Root (name = "Test")
#Order (elements = { "UserName", .... })
public class Test
{
#Element
public String UserName;
#Validate
public void validate() throws Exception
{
if(UserName.length() > 10) {
throw new Exception("User ID is invalid");
}
}
};
In the main code I write something like this
try {
serializer.read(REQ.class, reader);
}
catch(Exception ex) {
Log.i(TAG, ex.getMessage()); <--- HERE I GET MESSAGE: null, not the one I throws.
}
Question
Look like I can't catch exception which I throws, like validate function get my exception and replace it with it's own one. So am I right and what I can do to throw my own exception?
Thank you G.BlakeMeike you were right, the solution is follow:
try {
serializer.read(REQ.class, reader);
}
catch(Exception ex) {
Log.i(TAG, ex.getCause().getMessage());
}
I am doing Android Unit Test Case Execution and for Negative Test Case I should get exception, but for some API's Exception is not caught.
Please do find the example below:
public void testInsertSenderType_n() {
DBSms obj = new DBSms(getContext());
obj.open();
int i =0;
int a =0;
boolean result = true;
i=obj.GetToatlCount();
obj.insertSmsText(i+1,"Hello to testInsertSenderType_n");
a=obj.TotalcountSms("Inbox");
try
{
obj.insertSenderType(-100, "Richard", "Inbox", 0);
}
catch (Exception e)
{
// TODO: handle exception
result = false;
}
assertEquals(a,obj.TotalcountSms("Inbox"));
assertEquals(false,result);
obj.close();
}
Here in, obj.insertSenderType(-100, "Richard", "Inbox", 0); should throw an exception. But it is not thrown.
Please do guide where can I be Wrong.
I use following method to expect proper exception:
try {
doSomethingToProvokeException();
fail("there ought to be an exception dude, but was not");
} catch(ExeptionIHaveProvoked ex) {
doAssertionnsonThrowsException
}
You do not need variables to keeps exception state. As for why no exception is thrown in your code - nobody cann tell it to you, unless you provide source of object.
I am trying to use easyMock to write a test, that tests SecurityException in the following code.
eg. for NumberFormatException I use the below.
EasyMock.expect(mockEntityManager.find(UserProfile.class,"abc")).andThrow(new
NumberFormatException());
Any ideas on what to expect to throw SecurityException?
public Object getAsObject(FacesContext facesContext, UIComponent
uiComponent, String s) {
EntityManager entityManager = (EntityManager)Component.getInstance("entityManager");
if (s == null || s.equals("null")) {
return null; } else {
try {
long i = Long.parseLong(s);
return entityManager.find(UserProfile.class, i);
} catch (NumberFormatException e) {
logger.error(e);
} catch (SecurityException e) {
logger.error(e);
} }
return null; }
I have the feeling that you haven't written that code, and that's why you're wondering what might throw SecurityException. The answer is nothing, as long as you're using a good implementation of EntityManager.
The documented version of EntityManager.find()enter link description here doesn't throw SecurityException. BUT if you're running that code inside a J2EE app server that uses a custom version of EntityManager, it could be that it throws that exception... But I don't think it should.
Thanks for your responses..here is what I did to expect SecurityException.
MyClass abc = new MyClass();
EasyMock.expect(mockEntityManager.find(MyClass.class,111L)).andThrow(new SecurityException());
EasyMock.replay(mockEntityManager);
Object target = abc.getAsObject(mockFacesContext, mockUiComponent,"111");
Assert.assertEquals(null, target);
Basically, I am trying to generate a log file in Robocode, but I am having issues as you cannot use try/catch in Robocode (as far as I am aware). I have done the following:
public void onBattleEnded(BattleEndedEvent e) throws IOException
{
writeToLog();
throw new IOException();
}
and
public void writeToLog() throws IOException
{
//Create a new RobocodeFileWriter.
RobocodeFileWriter fileWriter = new RobocodeFileWriter("./logs/test.txt");
for (String line : outputLog)
{
fileWriter.write(line);
fileWriter.write(System.getProperty("line.seperator"));
}
throw new IOException();
}
and am getting the following error at compile time:-
MyRobot.java:123: onBattleEnded(robocode.BattleEndedEvent) in ma001jh.MyRobot cannot implement onBattleEnded(robocode.BattleEndedEvent) in robocode.robotinterfaces.IBasicEvents2; overridden method does not throw java.io.IOException
public void onBattleEnded(BattleEndedEvent e) throws IOException
^
1 error
As you can see here, the interface doesn't declare any checked exceptions. So you can't throw one in your implementing class.
One way to solve this would be to implement your method like this:
public void onBattleEnded(BattleEndedEvent e)
{
writeToLog();
throw new RuntimeException(new IOException());
}
public void writeToLog()
{
//Create a new RobocodeFileWriter.
RobocodeFileWriter fileWriter = new RobocodeFileWriter("./logs/test.txt");
for (String line : outputLog)
{
fileWriter.write(line);
fileWriter.write(System.getProperty("line.seperator"));
}
throw new new RuntimeException(new IOException());
}
but I am having issues as you cannot use try/catch in Robocode (as far as I am aware)
Where did this assumption came from? I just because of your question here installed robocode (so it's your fault if I'll answer here less often in future), wrote my own robot and it can catch exceptions quite good:
try {
int i = 1/0;
}
catch(ArithmeticException ex) {
ex.printStackTrace();
}
And why are you throwing IOExceptions in your example?