Surround With Try/Catch : comments issue
hi
Please consider this code:
public static void main(String[] pArguments)
FileInputStream vFileInputStream = new FileInputStream("someFile.txt");
// some comments, e.g. several lines of commented code (that might be uncommented later)
}It is possible to have JDeveloper "Surround With Try/Catch" this, but that results in this code:
public static void main(String[] pArguments)
FileInputStream vFileInputStream;
// some comments, e.g. several lines of commented code (that might be uncommented later)
try
vFileInputStream = new FileInputStream("someFile.txt");
catch (FileNotFoundException e)
// TODO
}Note that the declaration is before the comments and the try block starts after the comments.
Is this intentional behaviour? I would prefer to leave the comments where they are, after the (modified) code.
many thanks
Jan Vervecken
Thanks for your reply John.
I tried the right-click "Surround With..." > "try-catch" approach you suggest, and I get this code:
public static void main(String[] pArguments)
try
FileInputStream vFileInputStream = new FileInputStream("someFile.txt");
catch (FileNotFoundException e)
// some comments, e.g. several lines of commented code (that might be uncommented later)
}Indeed, the try-block starts before the comments.
There is another difference with this approach, the declaration is not separated from the assignment.
Next ... I'll try to remember which approach give which result. :)
regards
Jan
Similar Messages
-
RAISERROR with Try/Catch does not exit after exception in catch block
I am trying to propogate an error from within my proc out to the caller.
In the attached example I have 2 sets of try catch blocks.
I raiserror in the first
catch the error and then raiserror again. (I expect to exit)
I do not expect :
to get to print 'post test'
to get to second try block.
but this does not exit, instead the code flows as per 2 runs.
I do not understand the reason for the flows, as it seems counterintuitive to be raising an error but then still print following exceptions. I cannot seem to find any references that explains this behaviour.
running tests together results
print '-------------------------------------------------------'
print 'test 15'
exec test_raiseerror 15
print '-------------------------------------------------------'
print 'test 16'
exec test_raiseerror 16
print '-------------------------------------------------------'
print 'test 17'
exec test_raiseerror 17
print '-------------------------------------------------------'
print 'test 18'
exec test_raiseerror 18
print '-------------------------------------------------------'
'RESULTS'
test 15
error number provided: 15
Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 21
name hello 15
post test
15
Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 37
name hello 2 15
post test2
test 16
error number provided: 16
Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 21
name hello 16
post test
16
Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 37
name hello 2 16
post test2
test 17
error number provided: 17
post test
17
post test2
test 18
error number provided: 18
post test
18
post test2
Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 21
name hello 17
Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 37
name hello 2 17
Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 21
name hello 18
Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 37
name hello 2 18
run tests seperately
exec test_raiseerror 15
error number provided: 15
RESULTS 15
Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 21
name hello 15
post test
15
Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 37
name hello 2 15
post test2
exec test_raiseerror 16
RESULTS 16
error number provided: 16
Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 21
name hello 16
post test
16
Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 37
name hello 2 16
post test2
exec test_raiseerror 17
RESULTS 17
error number provided: 17
post test
17
post test2
Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 21
name hello 17
Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 37
name hello 2 17
exec test_raiseerror 18
RESULTS 18
error number provided: 18
post test
18
post test2
Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 21
name hello 18
Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 37
name hello 2 18
CODEBLOCK:
if object_id('test_raiseerror','P') is not null
drop proc test_raiseerror
go
create proc test_raiseerror(@id as int) as
begin
begin try
declare @name varchar(20)
select @name = 'hello'
raiserror('name %s %d',@id,1,@name,@id)
print 'next'
end try
begin catch
declare @errormessage nvarchar(4000)
declare @errornum int
select @errormessage = error_message()
, @errornum = error_severity()
print 'error number provided: ' + convert(varchar(2),@errornum)
raiserror(@errormessage, @errornum,1)
print 'post test'
end catch
begin try
select @name = 'hello 2'
raiserror('name %s %d', @id,1,@name, @id)
end try
begin catch
select @errormessage = error_message()
, @errornum = error_severity()
print @errornum
raiserror(@errormessage, @errornum,1)
print 'post test2'
end catch
end
go
sqlserver 2008 & 2008 R2There is a Connect that describes a similiar complaint. But basically a raiserror inside a catch block does not terminate the procedure, it will continue with any additional code in the CATCH and FINALLY unless it hits a return statement.
http://connect.microsoft.com/SQLServer/feedback/details/275308/have-raiserror-work-with-xact-abort -
How to accept 2 strings in a class with try catch method..help!!
the program below will accept two strings and compare str1 and str2 if equal. this program uses functions. can any one help me with this?
import java.io.*;
public class StrCompare {
private BufferedReader takyoin = null;
//private BufferedReader intakyo = null;
* @param args
public StrCompare(){
takyoin = new BufferedReader(new InputStreamReader(System.in));
//intakyo = new BufferedReader(new InputStreamReader(System.in));
public String UserInput(){
public static void main(String[] args) {
// TODO Auto-generated method stub
}What are you talking about? There is no such thing as "try-catch-methods", and there are no functions but methods.
Strings by the way have their own means of comparision. Apart from that: do your own homework. -
Please help with try/catch
Hello, I'm writing a program and I got surprised with the following. I've got the following try/catch block:
try {
String param = config.getConfigValue("db2.driver");
if (param == null)
// parameter not defined.
throw new Exception("Parameter 'db2.driver' missing!");
else
Class.forName(param);
catch (SQLException sqlEx) {
// do something
catch (Exception e) {
System.out.println("*** ERROR loading driver..."); (1)
finally {
releaseDB2Resources();
I know the program flow goes through the finally block, but it doesn't print the message (1). Why is that? I don't understand it. What am I doing wrong?
Thanks in advance.A finally block always gets executed, so that's why the println always works there. The only reason why the println in the catch wouldn't work is if that exception wasn't thrown. If a config value is not there, it might be the null string "" instead of null. Try this:
if (param.equals(""))
throw new Exception("blah");
You could also try:
if (true)
throw new Exception("blah");
to make sure that the exception is caught where you think it should be. -
Exception handling with try/catch in acrobat
Hi
I have a problem using a try/catch block in my acrobat document-script. Try to enter the following into the debugger-console:
try{nonexistentFunction();}catch(e){console.println('\nacrobat can't catch')}
and run it. The output will be:
nonexistentFunction is not defined
1:Console:Exec
acrobat can't catch
true
The whole point of a rty/catch block is for the application NOT to throw an exception, but instead execute the catch-part of the statement. However, acrobat does both: It throws an exception AND executes the catch-block.
Is there another way to suppress the exception, or to make the try/catch-block work as it's supposed to?> Also Adobe provides for free the JS or compiled file for Acrobat Reader to support the JS console.
Where is that file located ? How to install it or where to place it ?
What is the method referred by try67 on his site where he sells a product ?
Is that the same as the compiled file you refer to ? or did he sell his solution to adobe ?
It is helpful if people can get an idea of the nature of choices available and make informed decisions, than a cloak and dagger approach.
For some jobs that we have, I have been very frustrated by a consultant who wont even give basic info for transparent billing despite all assurances for privacy, as a result we are forced to do the job ourselves.
Dying Vet -
Hey everyone, I have a problem compiling this .java
import java.io.*;
public class lector
public static void main (String args[])
public void lector()
listapersonas listap = new listapersonas();
listaconocidos listac = new listaconocidos();
String linea, per, con;
persona nuevapersona,actual,nuevoconocido;
BufferedReader texto = new BufferedReader(new FileReader("conocidos.txt"));
linea="";
try {
while ((linea=texto.readLine())!=null)
per = linea.substring(0,linea.indexOf(','));
con = linea.substring(linea.indexOf(','));
nuevapersona = new persona(per);
nuevoconocido = new persona(con);
if (listap.existe(per)==false)
nuevapersona.conocidos.agregar(nuevoconocido);
listap.agregar(nuevapersona);
linea=texto.readLine();
continue;
if (listap.existe(per)==true)
if (listac.existe(con)==false)
listac.agregar(nuevoconocido);
else
linea=texto.readLine();
continue;
else
linea=texto.readLine();
continue;
} //while
} //try
catch (java.io.* e)
System.out.print("Imposible leer el archivo");
} //catch
} //lector
} // classWell what it is supposed to do is read a string from a file and then transform and add them to a linked list.
The problem is that when I compile there is an error message called "<identifier> expected" and points to the catch block. Please help meNothing weird about it at all.
That's not the syntax of a catch block. What you've written there will only work in an import statement.
What you probably mean to catch is java.io.IOException. -
i have a catch block as follows
catch (FileNotFoundException fnfe) {
System.out.println ("Library of Leng could not find a needed file.");
System.out.println (fnfe.printStackTrace());
JOptionPane.showMessageDialog (desktop, "File not found.", "ERROR", JOptionPane.WARNING_MESSAGE);
but when i compile it says that void is not allowed and highlights the line:
System.out.println (fnfe.printStackTrace());
but according to the api this is a valid method.
am i not reading this right or is java just fscked up?"am i not reading this right or is java just fscked up? "
The problem is ALWAYS between the chair and the monitor. There are way to many coders working with and on java for such a mistake to (still) be present.
In this case a "RTFM" was a proper response, because the javadocs clearly state that printStackTrace() returns void. -
TRY CATCH with dynamic ORDER BY
Some stored procs need a dynamic ORDER BY, unfortunately.
Can I use a TRY CATCH with ORDER BY?
SELECT ...
FROM ...
WHERE...
BEGIN TRY
ORDER BY ...complex stuff
END TRY
BEGIN CATCH
ORDER BY ColumnA
END CATCHHi mmmtbig,
Syntactically, it is ok to use any valid sql statement in the TRY AND CATCH block.
SELECT 1 as num
BEGIN TRY
SELECT 1/0 AS seq UNION SELECT 2 ORDER BY seq;
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE();
SELECT 1 AS seq UNION SELECT 2 ORDER BY seq;
END CATCH
For more details, You can reference
TRY...CATCH.
The confusion about your question is the "dynamic ORDER BY". What do you mean by that, can you elaborate your requirement, like in what scenario you'd like to use the code block in your post and what issue have stopped you from doing that?
If you have any feedback on our support, please click
here.
Eric Zhang
TechNet Community Support -
Is it possible try with out catch but with finally
can any body tell me that try with out catch but with finally is possible or not and also if I dont want to execute the finally block but i want to execute the try and catch then what can i do for that.
... and also if I dont want to
execute the finally block but i want to execute the
try and catch then what can i do for that.Obviously the best way then would be to not have the finally block at all.
But if you insist then add a boolean flag. Set it in the catch and test it in the finally block. -
Problem with a Try/catch exception
Hello everyone here on the forums. I'm brand new to Java and have a bit of a problem with a try catch statement I'm making. In the following code if a user enters a non-integer number the program will display "Sorry, incompatible data." Problem is it gets caught in a loop and continues to display "Sorry, incompatible data." My aim with the try catch was if the user is not quite smart enough to understand quadratic programs don't use symbols and characters it would state it isn't correct and continue running the program.
Heres my code thus far:
package finishedquadraticprogram;
import java.util.*;
* @author Matt
public class quad {
* @param args the command line arguments
public static void main(String[] args) {
boolean verification = true;
double a, b, c, root1, root2, discriminant;
Scanner keyInput = new Scanner(System.in);
while ( verification)
try
System.out.println("a: ");
a = keyInput.nextDouble();
System.out.println("b: ");
b = keyInput.nextDouble();
System.out.println("c: ");
c = keyInput.nextDouble();
discriminant = Math.sqrt(b * b - 4 * a * c);
root1 = (-b + discriminant) / 2 * a;
root2 = (-b - discriminant) / 2 * a;
verification = false;
System.out.println("Root 1 = " +root1+ "\nRoot 2 = " +root2);
} //try
catch (InputMismatchException iMe)
System.out.println( "Sorry. incompatible data." );
}I'm pretty sure the problem is something to do with the keyboard buffer, but I'm not sure what I need to do to either reset it or clear it, whichever one works. (Oh, and how would I go about making the program use complex numbers? I realize Java can't use complex numbers and will just display NaN ... any ideas how to make this work?)
Thanks a lot for all of your help guys, it's appreciated.this is better:
package finishedquadraticprogram;
import java.util.*;
/** @author Matt */
public class quad
private static final double TOLERANCE = 1.0e-9;
/** @param args the command line arguments */
public static void main(String[] args)
boolean verification = true;
double a, b, c, root1, root2, discriminant;
Scanner keyInput = new Scanner(System.in);
while (verification)
try
System.out.println("a: ");
a = keyInput.nextDouble();
System.out.println("b: ");
b = keyInput.nextDouble();
System.out.println("c: ");
c = keyInput.nextDouble();
discriminant = Math.sqrt(b * b - 4 * a * c);
if (Math.abs(a) < TOLERANCE)
root1 = 0.0;
root2 = -c/b;
else
root1 = (-b + discriminant) / (2 * a);
root2 = (-b - discriminant) / (2 * a);
verification = false;
System.out.println("Root 1 = " + root1 + "\nRoot 2 = " + root2);
} //try
catch (InputMismatchException iMe)
System.out.println("Sorry. incompatible data.");
keyInput.next();
} -
Need HELP with finally() in nested try-catch
hi,
i am having trouble with deadlock and wondering if its due to an incorrect use of finally nested within multiple try catch blocks.
is the inner finally() required, will the outer one get executed, or will the two finally() statements get executed...??
the deadlock happens very infrequently to accurately test.
try {
try {
catch (InterruptedException e) {
return;
catch {
finally {
//will this be executed be executed by the inner throw statement
}or is an inner finally required
try {
try {
catch (InterruptedException e) {
return;
//this finally is NEW....is it needed!
finally {
//will this be executed. will both get executed
catch {
finally {
//will this be executed also, or completely ignored if exception throw from inner try/catch
}inner/outer, which one is executed first?
more info pls.I mean, really. How hard is it to find out for yourself?
public class TestFinally {
public static void main(String[] args) {
try {
try {
throw new RuntimeException("Whatever");
} finally {
System.out.println("Inner finally");
} finally {
System.out.println("Outer finally");
}I'll leave it to your imagination as to how to modify this class to confirm the answers to your original question. -
Try/catch issue - "cannot find symbol - class InputMismatchExeption"
I'm still learning try/catch but from what i've read online and in the class library it looks right...i'm not sure why it won't compile.
try {
do {
System.out.print("Enter command (1-5): ");
selection = scan.nextInt();
if (selection < 1 || selection > 5) {
System.out.print("Illegal command number.");
System.out.println("The available commands are:");
System.out.println("\t1. Add new entry to the address book.");
System.out.println("\t2. Delete existing entry from address book entries.");
System.out.println("\t3. Print out all address book entries.");
System.out.println("\t4. Search records for a certain pattern.");
System.out.println("\t5. Quit the Application.");
while (selection < 1 || selection > 5);
//this does not work!!!!!!
catch( InputMismatchException ime ){
System.out.println("Illegal command.");
}I have
import.java.io.*;at the beginning before i declare my class. I'm not sure abotu the second thing you said, could you elaborate?
I'm sorry, I'm still new at java.
edit: yeah, I didn't import java.util.... hides in shame
Do i still have to import util.Scanner or will that import automatically when i import util.*
Message was edited by:
Cymae -
How to check a lot of conversion errors with one TRY-CATCH?
Hi,
I've to import a lot of data from a flatfile.
To avoid short dumps when there are non-numeric data's for a numeric field in the file, I load every record in a structure that have only CHAR fields.
Then I move this fields in a TRY-Catch block to the real fields like this:
TRY.
field1 = field_from_file1
field2 = field_from_file2
field3 = field_from_file3
CATCH cx_sy_conversion_no_number INTO lr_exception.
PERFORM fehler USING lr_exception.
ENDTRY.
This construct works until the first field has a conversion error. However I will test all fields to get a complete list of the errors. And I am to lazy to make a TRY-CATCH construct for hundred of move-statements.
Is there a better trick to check the success of <b>all</b> move operation?
Regards,
StefanHi Stefan,
sorry, the development system is down right now, so I could not test. But I'm convinced you can figure it out:
You may specify the parameters of a method as TYPE REF TO DATA.
Then, in the calling routine you may have
data:
anyrefsource type ref to data,
anyreftarget type ref to data.
GET REFERENCE OF p_source INTO anyrefsource.
GET REFERENCE OF p_target INTO anyreftarget.
call method try_conv
exporting
source = anyrefsource
target = anyreftarget.
and in the method:
ASSIGN source->* TO <fs_source>
and so on...
BTW: I know you have to use typed parameters in OO. Can't you use "TYPE ANY"?
regards,
C. -
Help with reducing try catch blocks
Hi,
I have an object of a class having about 100 get methods. I have about 300 such objects. I want to get all the parameters from all the 100 get methods for all the objects, and for each failed get methods, an exception occurs,
Now I can loop from - to no of objects but inside I have to declare 100 try catch methods for each get methods.
for(i=0;i< 300;i++) {
try {
a.getname;
catch { --- }
try{
a[i].getno ;
catch { -- }
100 such a[i].getXYZ methods
any alternative. wanted to avoid all the try catch statements
Please suggest
thankstarkesh wrote:
Its actually a serialized object, which I am trying to extract parameters from. So I actually need to know exactly which get method is failing for which object, as the objects can be in error when they get transported over the network.If it was me I would generate the code so the actual mechanism becomes moot.
But you can use something like the following (generated or not.)
String attrName="<Unknown>"
try
attrName = "attr1";
attr1=instance.attr1;
attrName = "attr2";
attr2 = instance.attr2;
catch(Exception e)
// attrName has correct name here.
} -
I know I posted this quesiton earlier,but I am sitll having problems. In the following code, the exception IS caught if the user enters a String instead of a Int. But the Exception is NOT caught if the user enters
the "Enter" key.
do
flag=false;
//set the quantity to user input
System.out.print("Enter the quantity:");
try
amount = input.nextInt();
if (amount > 0) //executes when amount is less then or equal to zero
flag=false;
} //end of if
else
System.out.println("You must enter a positive quantity");
flag=true;
} //end of try
catch (Exception e)
input.nextLine();
System.out.println("You must enter a number");
flag=true;
}while(flag==true); //end of do while
nextInt won't read "just the enter key"... it blocks until reads "something".
Try something like this instead...
Note: java.io.Console is new in 1.6
package krc.utilz.io;
// usage:
// import krc.utilz.io.Console;
// String name = Console.readLine("Enter your name : ");
// while ( (score=Console.readInteger("Enter a score between 0 and 100 (enter to quit) : ", 0, 100, -1)) != 1) { ... }
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public abstract class Console
private static final java.io.Console theConsole = System.console();
private static final DateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
public static String readLine(String prompt) {
while(true) {
try {
System.out.print(prompt);
return theConsole.readLine();
} catch (Exception e) {
System.out.println("Oops: "+e);
public static Date readDate(String prompt) {
while(true) {
try {
String response = readWord(prompt+" (dd/mm/yyyy) : ");
return dateFormatter.parse(response);
} catch (Exception e) {
System.out.println("Oops: "+e);
public static String readWord(String prompt) {
String response = null;
while(true) {
try {
response = readLine(prompt);
if( response!=null && response.length()>0 && response.indexOf(' ')<0 ) break;
System.out.println("A single word is required. No spaces.");
} catch (Exception e) {
System.out.println("Oops: "+e);
return(response);
public static char readLetter(String prompt) {
char c = '\0';
while(true) {
try {
String response = readLine(prompt);
if ( response!=null && response.length()>0 ) {
c = response.charAt(0);
if(Character. isLetter(c)) break;
System.out.println("A letter (A through Z) is required. Upper or lower case.");
} catch (Exception e) {
System.out.println("Oops: "+e);
return(c);
public static int readInteger(String prompt) {
int i = 0;
String response = null;
while(true) {
try {
response = readLine(prompt);
if ( response!=null && response.length()>0 ) {
i = Integer.parseInt(response);
break;
System.out.println("An integer is required.");
} catch (NumberFormatException e) {
System.out.println("\""+response+"\" cannot be interpreted as an integer!");
} catch (Exception e) {
System.out.println("Oops: "+e);
return(i);
public static int readInteger(String prompt, int lowerBound, int upperBound) {
int i = 0;
while(true) {
i = readInteger(prompt);
if ( i>=lowerBound && i<=upperBound ) break;
System.out.println("An integer between "+lowerBound+" and "+upperBound+" (inclusive) is required.");
return(i);
public static int readInteger(String prompt, int defualt) {
int i = 0;
String response = null;
while(true) {
try {
response = readLine(prompt);
return (response!=null && response.trim().length()>0
? Integer.parseInt(response)
: defualt
} catch (NumberFormatException e) {
System.out.println("\""+response+"\" cannot be interpreted as an integer!");
} catch (Exception e) {
System.out.println("Oops: "+e);
public static int readInteger(String prompt, int lowerBound, int upperBound, int defualt) {
int i = 0;
while(true) {
i = readInteger(prompt, defualt);
if ( i==defualt || i>=lowerBound && i<=upperBound ) break;
System.out.println("An integer between "+lowerBound+" and "+upperBound+" (inclusive) is required.");
return(i);
public static double readDouble(String prompt) {
double d = 0;
String response = null;
while(true) {
try {
response = readLine(prompt);
if ( response!=null && response.length()>0 ) {
d = Double.parseDouble(response);
break;
System.out.println("A number is required.");
} catch (NumberFormatException e) {
System.out.println("\""+response+"\" cannot be interpreted as a number!");
} catch (Exception e) {
System.out.println("Oops: "+e);
return(d);
public static double readDouble(String prompt, double lowerBound, double upperBound) {
while(true) {
double d = readDouble(prompt);
if ( d>=lowerBound && d<=upperBound ) return(d);
System.out.println("A number between "+lowerBound+" and "+upperBound+" (inclusive) is required.");
public static boolean readBoolean(String prompt) {
while(true) {
try {
String response = readWord(prompt+" (Y/N) : ");
return response.trim().equalsIgnoreCase("Y");
} catch (Exception e) {
System.out.println("Oops: "+e);
}
Maybe you are looking for
-
Notifications ... how do I stop getting email notifications?
Notifications ... how do I stop getting email notifications? I like this site but now I get 20-50 or more notifications a day in my email. I would rather shut that off and check back on my own now....
-
How distinguish between downpayment related to a downp. request from a DP
Hi to all, please, I need to find a criteria (usable in validation or substitution ) to dinstinguish a downpayemt (F-48) from a downpayment related to a downpayment request. Any idea or suggestion ? thanks to advance. Andrew
-
IPod won't display imported photos
I use iPod Photo mainly to upload photos from my digital camera in the field. It has always displayed a thumbnail of the pic in the little dotted box as they are imported, and afterwards they can be viewed and checked by selecting the Roll, then Brow
-
I opened iweb and previously saved sites that were not published are gone. Iweb is opening as if I had never saved anything. I did a spotlight search for domiain.sites and nothing is found. Any suggestions from anyone?
-
Document ype restriction in FBL5N for particular user
Hi all, I have a requirement where in we have to restrict document.type in fbl5n....... clients wants to give authorization to particular user only .They don't want to go for screen variant option.... i have define authorization group in oba7 and in