Custom Expcetion not throwing - java

The exception is never shown .
extended Exception class and override the method toString.and then called it.according to the condition it should display hahah , but it doesn't show anything..no errors either.
class Excp extends Exception {
public String toString() {
return "hahah";
}
}
public class exc {
boolean a = false;
void hey() throws Excp {
if (a)
throw new Excp();
}
public static void main(String... s) {
try {
new exc().hey();
} catch (Excp e) {
System.out.println(e);
}
}
}

Your condition
if(a)
will return false as you have intiialized a=false. Hence the if block will not execute the statement
throw new Excp();

Here
{
if(a)
throw new Excp();
}
A is false. Never goes in side the condition, because you haven't making true while initializing the object.
Try
try
{
Excp exc = new Excp();
exc.a= true;
exc.hey();
}
Side notes:
1)Please follow naming conventions.
2)Provide encapsulation.
3)Format your code always.

I think that you want to have a custom exception with your own error message, If so you can do like this
class MyException extends Exception{
MyException(String errorMsg){
super(errorMsg);
}
}
class Test{
public static void main(String[] args){
if(someCondition)
throw new MyException("My error message");
}
}

Related

Which close() runs first?

If I have multiple resources, in a try catch, which one gets closed called on first?
public class TestRes {
public static void main(String[] args) {
TestRes tr = new TestRes();
tr.test();
}
public void test() {
try (MyResource1 r1 = new MyResource1(); MyResource2 r2 = new MyResource2(); ) {
System.out.print("T ");
} catch (IOException ioe) {
System.out.print("IOE ");
} finally {
System.out.print("F ");
}
}
class MyResource1 implements AutoCloseable {
public void close() throws IOException {
System.out.print("1 ");
}
}
class MyResource2 implements Closeable {
public void close() throws IOException {
throw new IOException();
}
}
}
This sample outputs:
T 1 IOE F
If I change the order so...
public class TestRes {
public static void main(String[] args) {
TestRes tr = new TestRes();
tr.test();
}
public void test() {
try (MyResource2 r2 = new MyResource2(); MyResource1 r1 = new MyResource1();) {
System.out.print("T ");
} catch (IOException ioe) {
System.out.print("IOE ");
} finally {
System.out.print("F ");
}
}
class MyResource1 implements AutoCloseable {
public void close() throws IOException {
System.out.print("1 ");
}
}
class MyResource2 implements Closeable {
public void close() throws IOException {
throw new IOException();
}
}
}
I get the same output - why?
It seems that you believe an exception from a close() method will prevent other close() methods from being called. That is wrong.
The Java Language Specification, section 14.20.3. try-with-resources, says:
Resources are closed in the reverse order from that in which they were initialized. A resource is closed only if it initialized to a non-null value. An exception from the closing of one resource does not prevent the closing of other resources. Such an exception is suppressed if an exception was thrown previously by an initializer, the try block, or the closing of a resource.
Which means that the close() method printing 1 will always be executed, and the first part answers your "Which close() runs first?" question.

To break out main method in submethod without if-return or exception

I want to know if there is any way to break out the main method using its sub-method, but without throwing exceptions or returning a boolean.
For example
public void foo()
{
System.out.print("Trying to break out foo");
validate1();
validate2();
validate3();
System.out.print("Validation success");
}
public void validate1()
{
//todo: break out foo() if validation failed
}
public void validate2()
{
//todo: break out foo() if validation failed
}
public void validate3()
{
//todo: break out foo() if validation failed
}
No if( validate1() ) return; in foo().
No exception throwing in validate1(), validate2(), validate3().
Is that possible?
There is no such way to do so. You must get the response to your calling method and then break out of the calling method.
public void foo()
{
System.out.print("Trying to break out foo");
if(!validate1()) {
return;
}
if(!validate2()) {
return;
}
....
System.out.print("Validation success");
}
public boolean validate1()
{
try{
....
if(...) {
}
} catch(Exception e) {
//Don't throw exception. Instead just return false.
return false;
}
// no errors and validation passed
return true;
}
However, if you want the program to end, then you can simply do
public void validate1()
{
//todo: break out foo() if validation failed
System.exit(0); // abruptly close the program
}

Handle Exception after all lines have been finished execution without finally

I need methodA2 also gets executed even though there is an exception by methodA1(). Here I have added only two methods as methodA1() and methodA2(). Let's say there are many methods. In that case also, the solution should be able to applicable.
class A {
String methodA1() throws ExceptionE {
// do something
}
String methodA2() throws ExceptionE {
// do something
}
}
class C extends A {
String methodC() throws ExceptionE2 {
try {
methodA1();
methodA2();
} catch (ExceptionE e) {
throw new ExceptionE2();
}
}
}
Please note that there can be many methods invoked with methodA1, methodA2. In that case having multiple try, catch, finally will look ugly.. So are there any other methods to do that?
I need to store error information in a log file. In methodA1(), methodA2() ... information in each tag is get validated. what I want is having all the error information in log file. Once exception throws it will generate log file. So I will miss validation information from other tags. So we can't go for finally approach.
You can use a loop with Java 8 lambdas:
interface RunnableE {
void run() throws Exception;
}
class Example {
public static void main(String[] args) {
List<RunnableE> methods = Arrays.asList(
() -> methodA1(),
() -> methodA2(),
() -> methodA3()
);
for (RunnableE method : methods) {
try {
method.run();
} catch (Exception e) {
// log the exception
}
}
}
private static void methodA1() throws Exception {
System.out.println("A1");
}
private static void methodA2() throws Exception {
System.out.println("A2");
}
private static void methodA3() throws Exception {
System.out.println("A3");
}
}
Please note that the interface is needed only when methods throw checked exception. If they were throwing only runtime exceptions, you could use java.lang.Runnable instead.
No other way. If each method can throw exception, but you want to continue execution of remaining methods anyway, then each method call must be in its own try-catch block.
Example:
List<Exception> exceptions = new ArrayList<>();
try {
methodA1();
} catch (Exception e) {
exceptions.add(e);
}
try {
methodA2();
} catch (Exception e) {
exceptions.add(e);
}
try {
methodA3();
} catch (Exception e) {
exceptions.add(e);
}
if (! exceptions.isEmpty()) {
if (exceptions.size() == 1)
throw exceptions.get(0);
throw new CompoundException(exceptions);
}
You will of course have to implement the CompoundException yourself.

Executing code after exception is thrown

So I have a bit of situation here with my design and was wondering whether I could
get some feedback.
public class Class1 {
public void eatFish(){}
}
public class Class2 {
public void eatBacon(){
// some nasty code here to cause an exception
}
}
public class Class3 {
public void eatFruit(){}
}
public InvokeAllClasses() {
public static void main(String[] args) {
Class1 c1 = new Class1();
Class2 c2 = new Class2();
Class3 c3 = new Class3();
c1.eatFish();
c2.eatBacon();
c3.eatFruit();
}
}
See the problem here in InvokeAllClasses is that, because c2.eatBacon();
blows up, c3.eatFish() would not be executed. Is there a way to still execute
c3 although c2 blew up?
Update
After thinking more about, I guess I could wrap each call in a try...catch block but that is just messy.
Put the try...catch in the method defintion:
public void eatBacon(){
try{
// some nasty code here to cause an exception
} catch(Exception e){
//do something
}
}
This won't look as bad as putting it when you call the method. If you know where exactly in the code the exception could be happening, then only surround those statements.
You could handle the exceptions within the methods themselves so they aren't thrown back up to the calling method, but other than try/catch/finally blocks, there isn't a good practice way to ignore exceptions.
Unless you are sure that you will never have to handle any exceptions thrown by those methods, it might be better to avoid swallowing all of them at the source.
It's been a while since I wrote Java code and I could not try and compile it, but the idea is to create an object which has the responsability to execute tasks and swallow any exceptions.
It may look like:
public class SilentExecutor {
List<Runnable> tasks;
public SilentExecutor(List<Runnable) tasks) {
this.tasks = tasks == null? new List<Runnable>() : tasks;
}
public void execute() {
for (Runnable task : this.tasks) silentlyExecute(task);
}
private void silentlyExecute(Runnable task) {
try { task.run(); }
catch (Exception e) {}
}
}
Then your code could be something like:
new SilentExecutor(Arrays.asList(
() -> { c1.eatFish(); },
() -> { c2.eatBacon(); },
() - > { c3.eatFruit(); }
)).execute();
Why not just catch the exception and move on? I honestly don't think it will be messy.
Make your method to throw an exception.
public InvokeAllClasses() throws Exception {
public static void main(String[] args) {
Class1 c1 = new Class1();
Class2 c2 = new Class2();
Class3 c3 = new Class3();
try{
c1.eatFish();
}catch(Exception e){System.out.println("Oh noes! There was something wrong!!!")}
finally{
c2.eatBacon();
c3.eatFruit();
}
}
As you can see. The "finally" statement will force your code to perform no matter if the statement inside the try fails or throws an exception.
There are two approaches you could take. The first option is to ignore the exceptions completely.
try {
c1.eatFish();
} catch(Exception e) {//Ignore}
try {
c2.eatBacon();
} catch(Exception e) {//Ignore}
try {
c3.eatFruit();
} catch(Exception e) {//Ignore}
If you want the exception to be thrown in the end, you can put the result into a variable and then throw it at the end or use the finally clause.
try {
c1.eatFish();
finally {
try {
c2.eatBacon();
} finally {
c3.eatFruit();
}
}
If you are looking for something more readable, you could wrap the method calls.
public static void main(String[] args) {
Class1 c1 = new Class1();
Class2 c2 = new Class2();
Class3 c3 = new Class3();
callEatFishIgnoringException(c1);
callEatBaconIgnoringException(c2);
callEatFruitIgnoringException(c3);
}
private static void callEatFishIgnoringException(Class1 c1) {
try {c1.eatFish()} catch (Exception e) {//Ignore}
}
private static void callEatBaconIgnoringException(Class2 c2) {
try {c2.eatBacon()} catch (Exception e) {//Ignore}
}
private static void callEatFruitIgnoringException(Class3 c3) {
try {c3.eatFruit()} catch (Exception e) {//Ignore}
}

JUnit/TestNg: How to simplify/combine multiple { try fail() catch } for same exception?

Example (<Expected Exception> for assert 1 & assert 2 is same) :
#junit.framework.Test // or #org.testng.annotations.Test
public void testCase() {
try {
// assert 1
fail();
} catch (<Expected Exception>) {
}
try {
// assert 2
fail();
} catch (<Expected Exception>) {
}
}
If you're feeling adventurous, you can also try out assertThrows:
https://github.com/dsaff/junit.contrib
Feel free to ask if you have any problems.
If it's too hard to break this up into individual test methods, here's what's worked for me in the past.
Create a method expectsException() that expects a Callback.
interface Callback {
void call() throws Exception;
}
void expectsException(Callback callback) {
try {
callback.call();
fail("ExpectedException was not thrown!");
} catch (Exception e) {
if (!(e instanceof ExpectedException)) {
fail("Expecting ExpectedException, got " + e.getClass());
}
assertEquals("Expected exception message", e.getMessage());
}
}
Then, wrap up the code inside your try {...} catch blocks in the Callback:
#Test
public void testSomething() {
expectsException(new Callback() {
public void call() throws Exception {
// assert 1
}
});
expectsException(new Callback() {
public void call() throws Exception {
// assert 2
}
});
}
Note however, that depending on what you're doing in the catch block, this may or may not end up less verbose than a straightforward try {...} catch.
(When Java gets proper closures, then this approach will make a lot more sense.)
You should probably break your method into two separate methods that will each throw:
#Test(expectedExceptions = NullPointerException.class)
public void testCase1() {
// assert 1
}
#Test(expectedExceptions = NullPointerException.class)
public void testCase2() {
// assert 2
}
catch-exception might help:
public void testCase() {
// assert 1
verifyException(obj, MyException.class).do(1);
// assert 2
verifyException(obj, MyException.class).do(2);
}

Categories

Resources