public class exdemo1 {
public static void main(String args[]) {
int a = 10, b = 0, ans;
int arr[] = {10, 20, 30};
try {
ans = a / b;
System.out.println("Division" + ans);
System.out.println("4th Element" + arr[3]);
} catch (ArithmeticException ae) ;
{
System.out.println(ae);
}
catch (ArrayindexoutofboundsException ae) {
System.out.println(ae);
}
}
}
Now that your code is properly formatted, you will probably notice an extra ; after the first catch block.
I do not know what you mean exactly by that, but these are the issues I am noticing:
Your array does not have a 4th element, it has 3 elements, the last of which can be accessed through arr[2]
You can't divide by 0.
catch (ArithmeticException ae) ; You must remove the ; at the end of the line, you do not need that there.
ArrayindexoutofboundsException The proper class is ArrayIndexOutOfBoundsException.
I am assuming you know about the first two due to the catch statements.
Fixing those should make your program compile.
It is ArrayIndexOutOfBoundsException and not ArrayindexoutofboundsException
You have an extra semicolon after your first catch. Remove that. Also, I do not think ArrayindexoutofboundsException is a valid exception, should be ArrayIndexOutOfBoundsException?
You have mixed two programs together but only one Exception will be thrown. You program does basically the same thing as
public static void main(String... args) {
int a = 10, b = 0;
int ans = a / b;
}
This will print the exception thrown.
Related
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.
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.
public class Confusion {
Confusion(int i) {
int j = 5;
int[] a = new int[2];
try {
a[0] = 4;
if (i <= 0) {
int k = j / i;
} else {
System.out.println(j / i);
}
} catch (ArithmeticException sa) {
System.out.println("Wrong value" + sa);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("out of range massage in Class");
} finally {
System.out.println("Executing finally block in code");
}
}
void k() {
int[] a = new int[2];
{
try {
a[4] = 4;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("out of range");
}
}
}
}
public class Nested {
public static void main(String[] args) {
Confusion c = new Confusion(2);
Confusion c1 = new Confusion(0);
c1.k();
c.k();
}
}
Output:
-2
Executing finally block in code
Wrong valuejava.lang.ArithmeticException: / by zero
Executing finally block in code
out of range
out of range
Whenever i am executing the finally{} block written in the code below it is getting executed twice. Don't know why this is happening. I want to run the finally block only once.
Is there any way to throw multiple exception in single method?
It because you have two Confusion objects. Therefore, the constructor will be executed twice.
confusion c=new confusion(2);
confusion c1=new confusion(0);
confusion c=new confusion(2);
confusion c1=new confusion(0);
thats why u are getting 2 outputs from finally.
This is because you are creating two objects c1 and c
The finally block always executes when the try block exits.
http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
So regardless of any exception it will execute finally block. As you create two objects, it will call the constructor twice and will also execute finally twice.
You are calling the code in the try twice.
confusion c=new confusion(2);
confusion c1=new confusion(0);
This means that as the finally happens every time the try is called, it'll print...
Executing finally block in code
If you called it again,
confusion c1=new confusion(3);
It'd print out the contents of the finally a third time.
You are creating two objects using following code. Thats why the finally block is executed two times.
confusion c=new confusion(2);
confusion c1=new confusion(0);
Try this one please
public static void main(String[] args){
confusion c=new confusion(2);
confusion c1=new confusion(0);
confusion c1=new confusion(10);
confusion c1=new confusion(5);
}
Now finally block called 4 times.
Constructor in Java is block of code which is executed at the time of Object creation.
Please read constructor reference http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
Because you are creating two Confusion objects. Therefore, the finally block will be executed twice.
confusion c=new confusion(2);
confusion c1=new confusion(0);
If you want to execute finally only once.Try this code
public class Confusion {
Confusion(int i) {
int j = 5;
int[] a = new int[2];
a[0] = 4;
if (i <= 0) {
int k = j / i;
} else {
System.out.println(j / i);
}
}
void k() {
int[] a = new int[2];
a[4] = 4;
}
}
public class Nested {
public static void main(String[] args) {
try{
Confusion c = new Confusion(2);
Confusion c1 = new Confusion(0);
c1.k();
c.k();
}catch (ArithmeticException sa) {
System.out.println("Wrong value" + sa);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("out of range massage in Class");
} finally {
System.out.println("Executing finally block in code");
}
}
}
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"
I have the following code (it doesn't matter what it does, but for the curious, it's the start of an implementation of a square bending algorithm).
The problem is, it loops for no reason:
import java.util.*;
import java.io.*;
import java.lang.*;
class Solution
{
public static class kll
{
int ni;
int nj;
int pi;
int pj;
int v;
kll(){};
}
public static class g
{
static kll[][] a;
static int wh;
}
public static void f(int i1,int i2,int j1,int j2)
{
int nj1,nj2;
while (g.a[i1][i2].ni!=g.wh && g.a[i1][i2].nj!=g.wh)
{
i1=g.a[i1][i2].ni;
i2=g.a[i1][i2].nj;
}
while (g.a[j1][j2].ni!=g.wh && g.a[j1][j2].nj!=g.wh)
{
j1=g.a[j1][j2].ni;
j2=g.a[j1][j2].nj;
}
while (j1!=0)
{
nj2=g.a[j1][j2].pj;
nj1=g.a[j1][j2].pi;
g.a[i1][i2].ni=j1;
g.a[i1][i2].nj=j2;
g.a[j1][j2].pi=i1;
g.a[j1][j2].pj=i2;
i1=j1;
i2=j2;
j1=nj1;
j2=nj2;
}
g.a[i1][i2].ni=g.wh;
g.a[i1][i2].nj=g.wh;
}
public static void main(String[] args)
{
try
{
FileWriter oos1 = new FileWriter("output.txt");
File inTxt=new File("input.txt");
Scanner kbd = new Scanner(inTxt);
int input=kbd.nextInt();
kbd.close();
int number=(int)Math.pow(4,input);
g.wh=(int)Math.sqrt(number);
g.a=new kll[g.wh+1][g.wh+1];
for(int i=0;i<g.wh+1;i++)
for(int j=0;j<g.wh+1;j++)
g.a[i][j]=new kll();
for(int i=0;i<g.wh;i++)
for(int j=0;j<g.wh;j++)
{
g.a[i][j].ni=g.wh;
g.a[i][j].nj=g.wh;
g.a[i][j].pi=0;
g.a[i][j].pj=0;
g.a[i][j].v=0;
}
int separator=g.wh;
int half;
while(separator>1)
{
half=separator/2;
for(int i=0;i<half;i++)
for(int j=0;j<separator;j++)
f(j,i,j,separator-1-i);
for(int i=0;i<half;i++)
for(int j=0;j<separator;j++)
f(i,j,separator-1-i,j);
separator=half;
}
}
catch (FileNotFoundException ex) {}
catch(IOException ex) {}
}
}
Where have I gone wrong? That is, where is the infinite loop? What is causing it, and how can I fix it?
EDIT:
I have tried the debugger and it showed me that the infinite loop is here:
while (j1!=0)
{
nj2=g.a[j1][j2].pj;
nj1=g.a[j1][j2].pi;
g.a[i1][i2].ni=j1;
g.a[i1][i2].nj=j2;
g.a[j1][j2].pi=i1;
g.a[j1][j2].pj=i2;
i1=j1;
i2=j2;
j1=nj1;
j2=nj2;
}
I don't have any idea why it's infinite. j1 has got to be zero when it takes nj1 which is also zero. What's going wrong?
Simply put, j1 is never set to 0, because nj1 is never set to 0, because g.a[ji][j2].pi is never set to 0.
Place breakpoints and inspect g.a[ji][j2].pi -- you will see that it is never 0, given a particular set of arguments.
In particular, you will want to look at the arguments that feed your f() function that are causing that function to infinitely loop.
Once you have determined the problematic arguments, you can place an if-statement that causes a breakpoint to be hit before that function is called -- if you have not already determined why f() fails.