I written my own two customized Exception one is checked and other is unchecked
when i'm executing my code is shows only checked Exception Why i'm not able to get unchecked Exception output??
class Test {
public static void main(String args[]) throws CheckedException {
int i=0;
int j=0;
if(i==0){
throw new CheckedException("Got Checked Exception");
}
if(j==0){
throw new UncheckedException("Got Unchecked Exception");
}
}
}
class CheckedException extends Exception{
CheckedException(String s){
super(s);
}
}
class UncheckedException extends RuntimeException{
UncheckedException(String s){
super(s);
}
}
Output of above program is : Got Checked Exception
,But i'm expecting both output Got Checked Exception && Got Unchecked Exception. What mistake i'm doing here? and How can i overcome this?
In your program you have used throws in main() method and you have initialized i=0 and j=0.
the first if(i==0) satisfies and generated exception and program stopped. that is why second if condition part not executing.
if you want to check second condition initialize, i with something other than 0
like i=1 and execute
You can also use separate try catch block to test both cases
thank you
Related
I am trying to read a file using scanner in Java. I get the following output and error when I run the below piece of code.
Exception in thread "main"
java.lang.NullPointerException at
PageRank$ReadInput.ReadFile(PageRank.java:29) at
PageRank.main(PageRank.java:58)
Please help me fix this error.
public class PageRank{
public static class ReadInput{
private Scanner x;
public void OpenFile(){
try {
File file = new File("input.txt");
Scanner x=new Scanner(file);
}
catch(Exception e){
System.out.println("File does not exist.");
}
}
public void ReadFile() {
while (x.hasNextLine() ) {
String s = x.nextLine();
System.out.println(s);
String s1 = x.nextLine();
String s2 = x.nextLine();
System.out.println(s);
System.out.println(s1);
System.out.println(s2);
}
}
}
public static void main(String[] args)throws Exception
{
ReadInput P = new ReadInput();
P.OpenFile();
P.ReadFile();
}
}
In OpenFile(), inside the try block, you have to remove the 'Scanner' in
Scanner x=new Scanner(file);
and leave it as
x=new Scanner(file);
Explanation:
In your code, when you write
Scanner x=new Scanner(file);
inside the try block, you are creating a new variable but with the same name as the one you declared at the beginning of the class at
private Scanner x;
Now you would have two Scanner variables named 'x'. Inside the try statement, you are initializing the one inside that block, but it only exists there, so as soon you leave the try block it gets destroyed.
Now back to the ReadFile() function, you are calling x.hasNextLine(), but this 'x' is the one you declared at the beginning, not the one inside the try statement, so it is still uninitialized.
Below is the sample code I'm using to understand exception handling in completablefuture in java8.
If we make use of exceptionally method as per doc,
exceptionally method catches even runtime exception as well and proceeds to last block in the pipeline.
if we don't use exceptionally method then, it justs prints running and exits.
Correct me if my understanding isn't correct.
Question is Lets say if i want to throw runtime exception and want application to stop. Basically if i throw Runtime exception , it shouldn't proceed to next block in pipeline. How should i do that. Any pointers are helpful.
public static void main(String[] args) {
final CompletableFuture<String> retrieveName = CompletableFuture.supplyAsync(() -> {
System.out.println("running");
int i = 0;
if(i == 0) {
throw new RuntimeException("ding");
}
return "test";
}).exceptionally(it -> {
System.out.println(it.getMessage());
return "empty";
}).thenApply(it -> {
System.out.println("last block" + it);
return "dummy";
});
}
Try this:
public static void main(String[] args) {
try {
final CompletableFuture<String> retrieveName = CompletableFuture.supplyAsync(() -> {
System.out.println("running");
int i = 0;
if (i == 0) {
throw new RuntimeException("ding");
}
return "test";
}).exceptionally(it -> {
if (it.getMessage().contains("ding")) {
throw (RuntimeException) it;
}
System.out.println(it.getMessage());
return "empty";
}).thenApply(it -> {
System.out.println("last block" + it);
return "dummy";
});
retrieveName.join();
} catch (Exception e) {
System.out.println("main() exception, cause=" + e.getCause());
}
}
This is the output:
running
main() exception, cause=java.lang.RuntimeException: ding
I made 3 small changes to your code:
Wrapped it all in a try-catch
Threw a RuntimeException in exceptionally() for the "ding" exception.
Added a call to retrieveName.join(). From the Javadoc for CompletableFuture.join():
public T join()
Returns the result value when complete, or throws an (unchecked) exception if completed exceptionally.
Update based on OP feedback ------->
Lets say if i want to throw runtime exception and want application to
stop. Basically if i throw Runtime exception , it shouldn't proceed to
next block in pipeline. How should i do that.
You can achieve what you want with just 2 changes to your code:
[1] Completely remove the exceptionally() callback so the CompletableFuture (CF) terminates with an exception. In exceptionally() in the OP code the exception was being swallowed rather than rethrown, and returning a CF, so the thenApply() method was still performed.
[2] Add a call to retrieveName.join() at the end of main(). This is a blocking call, but since the thread had terminated with an exception that 's not really relevant for the sample code. The join() method will extract the thrown RunTimeException and re-throw it, wrapped in a CompletionException.
Here's your modified code:
public static void main(String[] args) {
final CompletableFuture<String> retrieveName = CompletableFuture.supplyAsync(() -> {
System.out.println("running");
int i = 0;
if(i == 0) {
throw new RuntimeException("ding");
}
return "test";
}).thenApply(it -> {
System.out.println("last block" + it);
return "dummy";
});
retrieveName.join();
}
Notes:
This is not how to do things in Production. The blocking call from join() was not a problem here, but could be for a long running CF. But you obviously can't extract the exception from the CF until it is complete, so it makes sense that the join() call blocks.
Always bear in mind that main() is not running in the same thread(s) as the CF.
An alternative approach (if viable) might be to handle all the necessary post-exception actions (logging, etc,) within exceptionally() and then terminate normally with a suitable return value (e.g. "Exception handled!") rather than propagating the exception.
You can check whether the CF is still running by calling the non-blocking isDone() method. You can also check whether the CF ended with an exception (isCompletedExceptionally()) or was cancelled(isCancelled()).
I have a method with a handled exception:
public boolean exampleMethod(){
try{
Integer temp=null;
temp.equals(null);
return
}catch(Exception e){
e.printStackTrace();
}
}
I want to test it
public void test_exampleMethod(){}
I have tried
#Rule
public ExpectedException expectedException=ExpectedException.none();
public void test_exampleMethod(){
expectedException.expect(JsonParseException.class);
exampleMethod();
}
but that doesnt work because the exception is handled inside.
I also tried
#Test(expected=JsonParseException.class)
but same issue...the exception is handled
I know that I can just do
assertTrue(if(exampleMethod()))
but it will still print the stack trace to the log. I would prefer clean logs...Any suggestions?
You cannot test what a method is doing internally. This is completely hidden (unless there are side effects, that are visible outside).
The test can check that for a specific input the method returns a expected output. But you can not check, how this is done. So you have no way to detect if there was a exception that you have handled.
So: either don't handle the exception (let the test catch the exception), or return a special value that tells you about the exception.
Anyway, I hope your real exception handling is more sensible than in your example.
If the method does not throw an exception you cannot expect to get one!
Below an example how write a Junit Test for a method that throws an Exception:
class Parser {
public void parseValue(String number) {
return Integer.parseInt(number);
}
}
Normal test case
public void testParseValueOK() {
Parser parser = new Parser();
assertTrue(23, parser.parseValue("23"));
}
Test case for exception
public void testParseValueException() {
Parser parser = new Parser();
try {
int value = parser.parseValue("notANumber");
fail("Expected a NumberFormatException");
} catch (NumberFormatException ex) {
// as expected got exception
}
}
I found some solution to rerun failed #Test in this forum at How to Re-run failed JUnit tests immediately?. In my case i execute the test from command line. And i want to rerun the complete test if it fails. Given below is my Test Script template and i want to rerun everything (from start to end) if it fails
#BeforeClass
public static void Start(){
...
}
#Test
public void Test_One(){
...
}
#Test
public void Test_Two(){
...
}
#AfterClass
public static void End(){
...
}
I will get to know in End() method if my test script has failed. If it fails, i would like to run everything like
#BeforeClass
#Test (all #Test)
#AfterClass
Is it possible with JUnit?
I am not sure if the template that i am using is correct :(
JanakiL,
It is a very good question. I tried to find some solution but i didn't manage to find clean solution for this task.
I can only propose to do some workaround that eventually will work.
So, in order to re-run suite you need to do following steps:
You need to create #ClassRule in order to execute whole suite.
All Suite you can retry using following code:
public class Retrier implements TestRule{
private int retryCount;
private int failedAttempt = 0;
#Override
public Statement apply(final Statement base,
final Description description) {
return new Statement() {
#Override
public void evaluate() throws Throwable {
base.evaluate();
while (retryNeeded()){
log.error( description.getDisplayName() + " failed");
failedAttempt++;
}
}
}
retryNeeded() – method that determines whether you need to do retry or not
This will retry all tests in your suite. Very important thing that retry will go after #AfterClass method.
In case you need to have “green build” after successful retry you need to write a bunch of another gloomy code.
You need to create #Rule that will not allow “publish” failed result. As example:
public class FailedRule extends TestWatcher {
#Override
public Statement apply(final Statement base, final Description description) {
return new Statement() {
#Override
public void evaluate() throws Throwable {
List<Throwable> errors = new ArrayList<Throwable>();
try {
base.evaluate();
} catch (AssumptionViolatedException e) {
log.error("", e.getMessage());
if (isLastRun()) {
throw e;
}
} catch (Throwable t) {
log.error("", t.getMessage());
if (isLastRun()) {
throw t;
}
}
};
};
}
}
isLastRun() – methods to verify whether it is last run and fail test only in case ir is last run.
Only last retry needs to be published to mark you test failed and build “red”.
3. And finally in your test class you need do register two rules:
#Rule
public FailedRule ruleExample = new FailedRule ();
#ClassRule
public static Retrier retrier = new Retrier (3);
In the Retrier you can pass count of attempts to retry.
I hope that somebody could suggest better solution !
More flexible solution is to write custom runner.
I described this answer in the following post:
How to Re-run failed JUnit tests immediately?
Using Eclipse, in the Junit view, you have a button "ReRun Tests - Failures First"
You can also see this answer: How to Re-run failed JUnit tests immediately?
I am facing a very peculiar situation. I am using hibernate template with spring 3.0.5 for DB operations. When I try to insert a User model the first time, a DataAccessException is thrown, which I catch. Now I wish to retry the same DB operation for say 3 times. The second time when it, no exception is thrown.
Here is the code:
package com.user.profile.dao;
#Repository("userProfileDAOImpl")
public class UserProfileDAOImpl implements IUserProfileDAO {
#Autowired
private HibernateTemplate hibernateTemplate;
public Long insertUserProfileData(User user) throws AppNonFatalException {
Long id = null;
int retryCount = 0;
while (retryCount < 3) {
try {
id = (Long)hibernateTemplate.save(user);
}
catch (DataAccessException e) {
e.printStackTrace();
retryCount++;
System.out.println("Retry Count = " + retryCount);
if (retryCount > 3) {
throw new AppNonFatalException(e.getLocalizedMessage(), "10000", e.getMessage(), e);
}
}
catch (Exception e) {
/* not coming inside this block too second time onwards */
System.out.println("Pure Exception");
}
}
return id;
}
}
I read that RuntimeExceptions should not be caught. Then how do I retry the operation. Should I retry at the service layer? Am I missing something? Any help is appreciated.
From https://community.oracle.com/docs/DOC-983543:
Unchecked exceptions are exceptions
that do not need to be declared in a
throws clause. They extend
RuntimeException. An unchecked
exception indicates an unexpected
problem that is probably due to a bug
in the code.
Since DataAccessException is a RuntimeException, you might want to check what is the real cause of the exception and fix it instead of catching it and retry the operation.