Exceptions and Output in Java [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I would like to be able to tell for sure when the compiler throws an exception with no output and when it's going to execute a few lines of code followed by an exception.
To further illustrate my point, consider the following code:
public class OverAndOver {
static String s = "";
public static void main(String[] args) {
try {
s += "1";
throw new Exception();
} catch (Exception e) { s += "2";
} finally { s += "3"; doStuff(); s += "4";
}
System.out.println(s);
}
static void doStuff() { int x = 0; int y = 7/x; }
}
A quick glance at the doStuff() method and you know the compiler is going to throw a Divide-by-zero exception.
Now, here's my question though (and the source of my confusion): Why didn't the compiler displayed "123" followed by the exception? And most importantly, how can I be able to tell for sure when the compiler is going to execute a few lines of code before throwing an exception and when it's going to throw an exception right away with no output?

Why didn't the compiler displayed "123" followed by the exception?
First of all, the compiler doesn't execute the code, so it will never display those values.
If you wonder why your app didn't display the text before the exception, the answer is that you didn't print it: you just append it to a string, and you print the string after the finally block.
The finally block throws an exception and your print statement will never be reached.
Try to print the text directly:
public class OverAndOver {
public static void main(String[] args) {
try {
System.out.println("1");
throw new Exception();
} catch (Exception e) {
System.out.println("2");
} finally {
System.out.println("3");
doStuff();
System.out.println("4");
}
}
static void doStuff() {
int x = 0;
int y = 7 / x;
}
}
The output will be:
1
2
3
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at com.jedisoftware.lf_delivery_tracking.OverAndOver.doStuff(App.java:74)
at com.jedisoftware.lf_delivery_tracking.OverAndOver.main(App.java:67)

Why didn't the compiler displayed "123" followed by the exception?
Because System.out.println(s); instruction is never executed.. Exception is raised in the doStuff(); method and the execution of main method is interrupted.
If you want to display 123 before the exception you should put the System.out.println(s); instruction before the doStuff() method as follows:
public class OverAndOver {
static String s = "";
public static void main(String[] args) {
try {
s += "1";
throw new Exception();
} catch (Exception e) { s += "2";
} finally { s += "3"; System.out.println(s); doStuff(); s += "4";
}
}
static void doStuff() { int x = 0; int y = 7/x; }
}

You call doStuff() which may throw an unchecked exception outside of a try block. If you want to print both the exception and the string you must wrap the doStuff() call in a try-catch construct.
public class OverAndOver {
static String s = "";
public static void main(String[] args) {
try {
s += "1";
throw new Exception();
} catch (Exception e) { s += "2";
} finally {
try{
s += "3"; doStuff(); s += "4";
}catch(ArithmeticException e){
e.printStackTrace();
}
}
System.out.println(s);
}
static void doStuff() { int x = 0; int y = 7/x; }
}

Related

Finally block excecution

When the below method is called it's printing output as 6 but I am expecting output as 5 as I have re-assigned n = 5 in the finally block.
Can anybody please help me with this?
public static int p() {
int n = 0;
try {
n = 6 ;
return n;
} catch (Exception e) {
return n;
} finally {
n = 5;
}
}
This can easily be answered by understanding the order of execution of your code. In your scenario you will always be returning the value of n before you hit the final block, in your code you will always be returning the value of 6. You will never return 5 (Final Block) or 0 (Catch Block).
So why would you never get 0?
You would never get 0 because the code within the try part of your try-catch-final statement will never in a million years throw any exception the way it has been written, so the catch statement is redundant.
So why would you never get 5?
You would never get 5 because the order of execution is return statement in the try block is executed first and then the final block runs. A try-final statement is the only statement I can think of (Happy to be proven wrong in comments) that any code is executed after a return statement is executed.
There is no reason why in your scenario you would have that final block unless for whatever reason you didn't trust the Garbage Collector was doing it's job, in which case you would nullify the n property here and that's it.
Your code could easily be re-written as the below because 6 is the only value your code will ever return.
public static int p() {
return 6;
}
As mentioned by luk2302 you are already return the value as 6. If you want to return the value as 5 then change your method as shown below.
public static int p() {
int n = 0;
try {
n = 6;
} catch (Exception e) {
return n;
} finally {
n = 5;
}
return n;
}
Question is very interesting, i even surprised why it is happening like that. When i checked about finally block i got the definition like below
"Java finally block is a block used to execute important code such as closing the connection, etc. Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be printed regardless of the exception occurs or not."
But i have compiled your program and saw how the compiled class looks like. It gives the answer
Original Java class
public class Finally {
public static int p() {
int n = 0;
try {
n = 6 ;
return n;
} catch (Exception e) {
return n;
} finally {
n = 5;
}
}
public static void main(String[] args) {
int n = p();
System.out.println("value of n " + n);
}
}
Compiled class
public class Finally {
public Finally() {
}
public static int p() {
byte n = 0;
byte var2;
try {
n = 6;
byte var1 = n;
return var1;
} catch (Exception var6) {
var2 = n;
} finally {
boolean var8 = true;
}
return var2;
}
public static void main(String[] args) {
int n = p();
System.out.println("value of n " + n);
}
}
As you can see how return statements translated due to that we don't see the value which is assigned in finally block instead we see value which is assigned in the try block.
Hope that clarify your answer.

When does try-with-resources close the resource?

I'm preparing myself for fall exam in Object Oriented Programming and one type of tasks we are given is providing output from code which usually consists of some Exception handling problems.
Now my question is when does try-with-resources close it's resource because my output is strictly dependent on output from class that implements AutoCloseable.
In provided code, what I don't understand why "close 1" output comes before "close 40", or why is object A(40) closed at the end of this block. Is it because A(50) is same type as A(40)?
My main question when does the AutoCloseable close the given resource, like in example m1 when i=1:
1) A(1) is created
1b) Try block is executed
2) A(1) is closed
3) ArrayIndexOutOfBoundsException is handled?
public class Main {
public static void main(String[] args) {
int[] arr = new int[] { 15, 10 };
for(int i=1; i>=-1; i--){
try(A a40 = new A(40)) {
m1(arr, i);
A a50 = new A(50);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("array exc");
}
catch(Exception e) {
System.out.println("main exc");
break;
}
finally {
System.out.println("main finally");
}
}
System.out.println("main done");
}
private static void m1(int[] arr, int i) throws Exception {
try(A a1 = new A(i)) {
m2(arr[i] + arr[i+1], i);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("m1 exc");
}
System.out.println("m1 done");
}
private static int m2(int x, int y) {
int r = 0;
try{
A a2 = new A(x+y);
r = x / y;
}
finally {
System.out.println("m2 finally");
}
System.out.println("m2 done");
return r;
}
}
And class A which implements AutoCloseable:
public class A implements AutoCloseable {
private int x;
public A(int x){
this.x = x;
System.out.println("A " + x);
}
#Override
public void close() throws Exception {
System.out.println("close " + x);
}
}
Here is output of provided code:
A 40
A 1
close 1
m1 exc
m1 done
A 50
close 40
main finally
A 40
A 0
A 25
m2 finally
close 0
close 40
main exc
main finally
main done
The specification is pretty clear on this.
14.20.3. try-with-resources
A try-with-resources statement is parameterized with local variables (known as resources) that are initialized before execution
of the try block and closed automatically, in the reverse order from
which they were initialized, after execution of the try block.
Your example is a bit convoluted. Try to simplify it. There are two scenarios you are interested in: an exception thrown in the try block, an exception isn't thrown in the try block. You debugging messages is informative, so you will be able to track the flow easily.
You may want to look into decompiled .classes to see what actually was generated.

Avoiding nested try/catch

import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String str = input.next();
int a;
try{
try{
a = Integer.parseInt(str);
}
catch(NumberFormatException nfe){
throw new CustomException("message");
}
if (a>50) throw new CustomException("message");
}
catch(CustomException e){
//do something
}
}
}
If str is something other than numbers, parseInt will throw a NumberFormatException. But I want to 'convert' it so that I'll have a CustomException with "message" instead. Can I do this without using a nested try/catch blocks like above?
you could refator your example to
try {
a = Integer.parseInt(str);
if (a > 50) {
throw new CustomException("message");
}
} catch (NumberFormatException | CustomException e){
//do something
}
Use the Scanner.hasNextInt() to parse the int without worrying about exceptions.
see this question for detailed code.
You could write:
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String str = input.next();
int a;
try{
a = Integer.parseInt(str);
if (a>50) throw new NumberFormatException("message");
}
catch(NumberFormatException e){
//do something
}
}
but I suggest you to use your version, since the code is more readable. My version, even if removes the inner try, is less readable than yours.

Error: cannot find symbol for Exceptions in Java

I am writing a very simple program in Java that tries to divide 10 by a user-entered number and catches a DivideByZeroException. Here is the code:
public class EnhancedCatchExceptions6 {
public static void main(String[] args) {
System.out.println();
for (int i = 0 ; i < i; i++) {
try {
int b = Input.getInt("Enter an integer to divide by:");
divide(10, b);
break;
} catch (DivideByZeroException e) {
System.out.println("Error: Divided by zero. Try again.\n");
}
}
}
public static int divide(int x, int y) throws DivideByZeroException {
System.out.println();
int result = 0;
try {result = x/y;}
catch (ArithmeticException e) {throw new DivideByZeroException(y);}
return result;
}
}
For some reason is returns an error: cannot find symbol for every 'DivideByZeroException.' If I change DivideByZeroException to Exception it does not return that error. The same error appears when I was writing other programs with other exceptions.
I don't understand why this error is returned and I would appreciate any help. Thanks!
Most likely this is happening because you forget to import your DivideByZeroException. Change the first lines of your class adding:
import your.package.name.DivideByZeroException;
and you should be fine. Do not forget to use real package name of yours, of course.
The other guess - if you want a class that represents an exception and comes with JDK, not your own, consider replacing DivideByZeroException with ArithmeticException.

Why do I keep getting the "must be caught or declared to be thrown" error? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Here is my code
import java.io.*;
import java.util.*;
import java.util.Scanner;
import java.io.PrintWriter;
public class EncryptionDecryption {
public static void main(String[] args) throws java.io.IOException{
int z = getRandom();
boolean luck = true;
while(luck == true){
String codeString = getString();
System.out.println(codeString);
char[] enCharArray = encrypt(codeString, z);
String encryptedString = new String(enCharArray);
System.out.println(encryptedString);
char[] deCharArray = decrypt(encryptedString, z);
String decryptedString = new String(deCharArray);
System.out.println(decryptedString);
putString(encryptedString);
if(codeString.length() == 0)
luck = false;
}
}
static String getString(){
Scanner input = new Scanner(new File(" "));
String codeString = input.next();
return codeString;
}
static void putString (String finalString){
PrintWriter work = new PrintWriter("EncryptedDocument.txt");
work.print(finalString + " ");
work.close();
}
static char[] encrypt(String encryptString, int z){
char[] codeChar = encryptString.toCharArray();
char[] enCharArray;
enCharArray = new char[codeChar.length];
for(int i = 0; i < codeChar.length; i++){
int x = codeChar[i];
int enInt = encryptChar(x, z);
char enChar = (char)enInt;
enCharArray[i] = enChar;
if(x == 32){
enInt = 32;
enChar = (char)enInt;
enCharArray[i] = enChar;
}
}
return enCharArray;
}
static char[] decrypt(String decryptString, int z){
char[] deCodeChar = decryptString.toCharArray();
char[] deCharArray;
deCharArray = new char[deCodeChar.length];
for(int i = 0; i < deCodeChar.length; i++){
int x = deCodeChar[i];
int deInt = decryptChar(x, z);
char deChar = (char)deInt;
deCharArray[i] = deChar;
if(x == 32){
deInt = 32;
deChar = (char)deInt;
deCharArray[i] = deChar;
}
}
return deCharArray;
}
static int encryptChar(int x, int z){
int y = 'A';
int enInt = (x - y + z) % 26 + y;
return enInt;
}
static int decryptChar(int x, int z){
int y = 'A';
int deInt = (x - y + 104 - z) % 26 + y;
return deInt;
}
static int getRandom(){
int encryptMethod = 0;
while(encryptMethod == 0){
Random encrypt = new Random();
encryptMethod = encrypt.nextInt(96);
}
return encryptMethod;
}
}
I keep getting these errors when i try to compile:
EncryptionDecryption.java:32: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
Scanner input = new Scanner(new File(" "));
^
EncryptionDecryption.java:38: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
PrintWriter work = new PrintWriter("EncryptedDocument.txt");
^
2 errors
Because you call a method that declares that it throws a FileNotFoundException, and you don't catch the exception, nor do you declare that the enclosing method throws it. This is not allowed in Java. All checked exceptions must either be caught, or declared in the throws clause of the method:
static String getString() throws FileNotFoundException {
If you can handle the exception and do something meaningful that makes you program continue to work as expected, then catch the exception. If you can't handle it in this method, then let the caller of your method handle it for you, and let it propagate by declaring it in the throws clause.
In the method getString() You are creating a new File(), which throws FileNotFoundException. This FileNotFoundException must be caught by enclosing the scanner code block with in the try-catch block or declared thrown by the method. Same thing applies to the putString (String finalString) method.
Your code should be
static String getString(){
Scanner input;
try {
input = new Scanner(new File(" "));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String codeString = input.next();
return codeString;
}
static void putString (String finalString){
PrintWriter work;
try {
work = new PrintWriter("EncryptedDocument.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
work.print(finalString + " ");
work.close();
}
Notice how you have...
public static void main(String[] args) throws java.io.IOException
with that "throws" line there? That's to tell Java that when an IOException occurs, it should be passed up to whatever called main().
Java requires that you do this for any possible exception that might be raised. What those error messages are telling you is that there are 2 other types of exceptions that might be raised in your code; you need to specify that they're thrown (or otherwise handle them yourself, via a try/catch block).
try adding a
throws java.io.IOException
to any METHOD that uses file IO as well. I think it will solve your problem
Because FileNotFoundException is a checked Exception which means in Java that you have to do something with them when they occur.
You have two options to handle checked exceptions:
catch them and do something with them try{
} catch(FileNotFoundException e) { //do something with e}
re-throw them, which means add the line throws FileNotFoundException add the end of your method signature
In the code above Scanner input = new Scanner(new File(" ")); indicate that you are trying to open a file.Now this might or might not be available when you are trying to open it.Hence a exception is thrown if it is not available at that time.Hence it is always recommended to handle this code correspondingly.
must be caught or declared to be thrown indicate that we may expect an exception such as above explained can be thrown by the code and hence must be handled.Exception handling is done using either
1.use try catch
try{
ur code that generates exception
}
catch{
handle exception
}
This illustrates the first part of the exception you got "must be caught"
2.use throw
when you dont want to handle the exception right here you can throw it to the method that is calling it.The calling method must handle this exception.
meth1()
{
meth2();
}
meth2()throws Exception
{
try{
.....
.....
}
catch(Exception e)
{
...
u will not handle it here;
throw e; //exception thrown to the calling method meth1()
}
}
This illustrates the
second part of the exception "declared to be thrown"

Categories