why the first compiles but second doesn't - java

import static java.lang.System.*;
import java.io.*;
public class ExceptionDemo {
public static void main(String args[]) {
try {
int x = 5/0;
}finally {
System.out.print("exception ");
}
}
}
import static java.lang.System.*;
import java.io.*;
public class ExceptionDemo {
public static void main(String args[]) {
try {
throw new Exception();
} finally {
System.out.print("exception ");
}
}
}

You have two choices here :
Either catch the exception you're throwing :
public static void main(String args[]) {
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.print("exception ");
}
}
Either make your method throw it :
public static void main(String args[]) throws Exception {
try {
throw new Exception();
} finally {
System.out.print("exception ");
}
}
But you have to handle it anyway. My own preference being catching it and handling it directly.

Related

how to avoid Infinite Recursion in a non-return method with Try catch

public class Sample {
public static void main(String[] args) {
method();
}
public static void method()
{
try {
System.out.println("function");
throw new StaleElementReferenceException("thih sexception occured");
}
catch (StaleElementReferenceException e) {
method();
}
catch (Exception e) {
System.out.println("AssertFail");
}
}
}
how to avoid Infinite Recursion in a non-return method with Try catch...For Example this code below...when the StaleElementException Occurs only once i want to execute "functions after Exception , if the Stale Element occurs the second time i want it to go to Exception catch and print Assert fail..how?
public class Sample {
public static void main(String[] args) {
method(false);
}
public static void method(boolean calledFromCatchBlock)
{
try {
System.out.println("function");
if(!calledFromCatchBlock) {
throw new StaleElementReferenceException("thih sexception occured");
} else {
throw new Exception();
}
} catch (StaleElementReferenceException e) {
method(true);
} catch (Exception e) {
System.out.println("AssertFail");
}
}
}
You should store somehow the state when you throw an exception (e.g. a boolean flag) outside method(), check this state and throw modified exception next time:
private static boolean alreadyThrown = false;
public static void method()
{
try {
System.out.println("function");
if (alreadyThrown) {
throw new RuntimeException("another exception occured");
} else {
alreadyThrown = true;
throw new StaleElementReferenceException("this exception occured");
}
}
catch (StaleElementReferenceException e) {
method();
}
catch (Exception e) {
System.out.println("AssertFail");
}
}
Or you could provide some argument to the method(int arg) and check its value in a similar way:
public static void main(String[] args) {
method(1);
}
public static void method(int arg)
{
try {
System.out.println("function");
if (arg > 1) {
throw new RuntimeException("another exception occured");
} else {
throw new StaleElementReferenceException("this exception occured");
}
}
catch (StaleElementReferenceException e) {
method(arg + 1);
}
catch (Exception e) {
System.out.println("AssertFail");
}
}

synchronized not work ,still java.util.ConcurrentModificationException

I have the following Java code:
But the synchronized not work well, Help!
java.util.ConcurrentModificationException
java.util.ConcurrentModificationException at
java.util.HashMap$HashIterator.nextNode(HashMap.java:1442) at
java.util.HashMap$KeyIterator.next(HashMap.java:1466) at
java.util.AbstractCollection.toArray(AbstractCollection.java:196) at
Main.m(Main.java:68) at Main.lambda$main$0(Main.java:25) at
java.lang.Thread.run(Thread.java:748)
public class Main {
public static Set<Object> objectSet = new HashSet<>();
public static void main(String[] args) throws Exception {
new Thread(()->{m();}).start();
new Thread(()->{add();}).start();
}
public static void add() {
while (true){
objectSet.add(new Object());
}
}
public static void m(){
while(true){
try {
synchronized (objectSet) {
List a = Arrays.asList(objectSet.toArray(new Object[0]));
System.out.println(a.size());
}
}catch (Exception e){
e.printStackTrace();
}
try {
Thread.sleep(1000);
}catch (Exception e){
}
}
}
}
Can't synchronize (java.util.ConcurrentModificationException)
The writers should also synchronize on the same object
Change the add method as
public static void add() {
while (true) {
synchronized (objectSet) {
objectSet.add(new Object());
}
}
}

Java Program Error saying class , interface or enum expected

import java.io.*;
public class Test13
{
public static void main(String[] args) throws IOException
{
FileInputStream fis1 = new FileInputStream("D:/abc.txt");
FileInputStream fis2 = new FileInputStream("D:/xyz.txt");
SequenceInputStream sis = new SequenceInputStream(fis1,fis2);
int i;
while((i = sis.read())!=-1)
{
System.out.println((char)i);
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
I think you tried something like that. I inserted some explenations to the Exception-Handling
import java.io.FileInputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
public class Test13 {
//because all exceptions are already catched main will never throw one
public static void main(String[] args) throws IOException {
try {
//if an exception raises anywhere from here ...
FileInputStream fis1 = new FileInputStream("D:/abc.txt");
FileInputStream fis2 = new FileInputStream("D:/xyz.txt");
SequenceInputStream sis = new SequenceInputStream(fis1, fis2);
int i;
while ((i = sis.read()) != -1) {
System.out.println((char) i);
}
//... to here ...
} catch (Exception ex) {
//this catch block code will be executed
ex.printStackTrace();
}
}
}
You should have
try{
//function which throws exceptions
}
catch( SpecificException e ) {
// if a specific exception was thrown, handle it here
}
catch(Exception ex) {
// if a more general exception was thrown, handle it here
}
finally{
}
Below is the updated code and its working fine.
import java.io.*;
public class Test13
{
public static void main(String[] args) throws IOException {
try {
FileInputStream fis1 = new FileInputStream("D:/abc.txt");
FileInputStream fis2 = new FileInputStream("D:/xyz.txt");
SequenceInputStream sis = new SequenceInputStream(fis1, fis2);
int i;
while ((i = sis.read()) != -1)
{
System.out.println((char) i);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Creating a Custom Exception

I'm trying to create a method f1(x) that throws an exception when x equals 5. After that I will try to call that method from another method f2() to invoke that exception. Then I have to have f2() recover by calling f1(x+1). I tried coding something, but I'm stuck. Here is the code:
public class FiveException extends Exception {
public void f1(int x) throws FiveException {
if (x == 5) {
throw new FiveException();
}
}
public void f2() {
int x = 5;
try {
f1(x);
}catch (FiveException e) {
System.out.println("x is 5");
}
}
public static void main(String[] args) {
FiveException x5 = new FiveException();
x5.f2();
}
}
The print statement works, but I'm not sure how to call f(x+1). Any help on how to fix this and any techniques to write exceptions is appreciated.
Because f1 throws FiveException, wherever you call f1 you must either catch the exception or throw it to the method calling the method that raises the exception. For example:
public static void main(String[] args) throws FiveException {
FiveException x5 = new FiveException();
x5.f1(1);
}
Or:
public static void main(String[] args) {
FiveException x5 = new FiveException();
try {
x5.f1(1);
} catch (FiveException e) {
e.printStackTrace();
}
}
But your code is confusing... normally, it isn't the exception class that throws itself, you have other classes that throw the exception class.
If it's being invoked inside a catch statement, you must surround it with another try-catch, 'cause the code inside catch isn't protected, like this:
public void f2() {
int x = 5;
try {
f1(x);
}catch (FiveException e) {
System.out.println("x is 5");
try {
f1(x + 1);
} catch (FiveException e) {
e.printStackTrace();
}
}
}
But this code is ugly, you can write the following:
public void f2() {
int x = 5;
fProtected(x);
fProtected(x + 1);
}
private void fProtected(int x) {
try {
f1(x);
}catch (FiveException e) {
System.out.println("x is 5");
}
}

try-catch arround callback

public class Test {
public static void main(String[] args) {
try {
doSomething(new TestCallback() {
#Override
public void doCallback() {
throw new NullPointerException();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public static void doSomething(TestCallback callback){
callback.doCallback();
}
interface TestCallback {
public void doCallback();
}
}
RESULT:
java.lang.NullPointerException
at managers.concurrency.Test$1.doCallback(Test.java:11)
at managers.concurrency.Test.doSomething(Test.java:20)
at managers.concurrency.Test.main(Test.java:8)
In the above code we will get NullPointerException because the callback code is executed in the different part of stack. Is there a way to catch the such exceptions locally?
You are already catching the exception. Try something as follows -
try {
doSomething(new TestCallback() {
#Override
public void doCallback() {
throw new NullPointerException();
}
});
} catch (Exception e) {
System.out.println("Exception caught !!!");
}
Output:
Exception caught !!!

Categories

Resources