Return statement inside try block
what is wrong if i write code like as below...please explain me since i am new to java
class sample{
public String method(){
try{
String str="abc";
return abc;
catch(Exception e){}
}
veldhanas wrote:
return abc;In your code there is no varible declared as abc. It is a value assigned in str.
Suppose if the code in try statement throws exception the return statement is skipped and the
associated catch block will get executed. So your catch block must return a result of type String.... or throw another (or the same) exception.
In this case, since there's no way the code in the given "try" block can throw an exception, it would have been better to not even have a try/catch block in the first place.
And almost never just swallow exceptions like that (an empty catch block). There are only a few cases where it's ok to swallow them (such as in finally blocks where you're cleaning up resources which may throw exceptions while cleaning up, and you want to continue cleaning up and ignore those kinds of exceptions).
Similar Messages
-
Return statement inside a catch block???
If you put a return statement inside of a catch block, what statements will be executed next? I.e., what happens to the flow of control?
If you put a return statement inside of a catchblock, what statements will be executed next? I.e.,
what
happens to the flow of control?If you write a short testing sample, compile it and
run it, what do you get as a result ?
Eek! That actually involves effort! Are you kidding?Kidding ? Me ?
I'd better waste my time writing programs for lazy OPs !
;) -
Return statement in catch block !
Hello Java Gurus,
The code is not compiling when i remove return from the catch block
i dont really understand the essence of return statement in catch block
any help is greatly appreciated !
Thanks in advance !
import java.io.*;
public class fileinputstream {
public static void main(String arg[]) {
FileInputStream fin ;
FileOutputStream fout;
try {
fin =new FileInputStream("input_file.txt");
int bytes_av = fin.available();
System.out.println("bytes available the input file "+bytes_av);
catch(FileNotFoundException e)
System.out.println("The input file is not present");
return;
catch(IOException e)
System.out.println("error while giving bytes available the input file");
return;
try
fout =new FileOutputStream("output_file.txt");
catch(FileNotFoundException e)
System.out.println("The output file cannot be created");
return;
int data=0;
try {
data =(int)fin.read();
catch(IOException e) {
System.out.println("Exception while reading from file");
while(-1!=data) {
try
fout.write(data);
catch(IOException e)
System.out.println("Error while writing to file");
try
data =(int)fin.read();
catch(IOException e)
System.out.println("Exception while reading from file");
try {
fin.close();
fout.close();
catch(IOException e) {
System.out.println("Error while closing files");
}You do understand what "return" means, don't you? It
exits the method, main() in this case.
So the return statements in the catch blocks end the
program. If you remove the return statements, the
program will continue with the code after the catch
blocks. It needs the variables "fout" and "fin"
there, and these must be initialised.
If there are no return statements in the catch
blocks, the variables "fin" and "fout" will be not
initialized when you get to the code that uses them,
and that's an error. The java compiler is telling you
that you must always initialise the variables (you
can set them to "null", for example).Great explanation !!!
Thanks ! -
Return statement inside AddEventListener?
I am writing a custom function that will add a component to
the stage. However, I want to postpone adding this component until
some data has been loaded. Problem is that placing the return
statement inside the Event handler function won't work, because it
would be interpreted as a return statement for the Event handler
function. Is there a way to for instance refer to the parent
function?"Jurgen Beli?n" <[email protected]> wrote in
message
news:gq7jbs$7i4$[email protected]..
>I am writing a custom function that will add a component
to the stage.
>However,
> I want to postpone adding this component until some data
has been loaded.
> Problem is that placing the return statement inside the
Event handler
> function
> won't work, because it would be interpreted as a return
statement for the
> Event
> handler function. Is there a way to for instance refer
to the parent
> function?
>
> private function addDrawer(...):Drawer {
> var newDrawer:Drawer = new Drawer();
>
> drawerContentLoader.addEventListener(Event.COMPLETE,
function
> (event:Event):void {
> newDrawer.DrawerContentXml =
XML(drawerContentLoader.data);
>
> // return newDrawer when loaded.
>
> });
> drawerContentLoader.load(drawerContentRequest);
>
> return newDrawer;
> }
Why not just put your logic inside the handler for the event
where the data
exists for you to actually be able to populate it? -
While local variable initialized inside try block compiler throws error???
Check out this code where two local variables(one String and the other int type) is declared at the beginning of the method and initialized inside try block. now when i compile this app, it gives an error sayin' that Variables not been initialized. Can anyone tell me why compiler is throwin' an error message?
Many thanks.
import java.io.*;
public class Test{
public static void main(String[] args){
String aa;
int c;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("EnterAnything:");
try{
aa = in.readLine();
c = 1;
catch(IOException e){
System.out.println(e.getMessage());
System.out.println(aa);
System.out.println(c);
}jfbriere,
Thanks to u all.
that every reference to the variable is necessarily preceded
by execution of an assignment
to the variable.But I've initialized the variable c and aa inside try block before referencing it as a parameter of println()?
Can u clarify this?
--DM -
Posiibility for terminating jvm inside try block so that finally block wont
posiibility for terminating jvm inside try block so that finally block wont execute at all ?
But in that case what will happen?
Is it safe for any practical situation ?
Threads: t.stop()
JVM : System.exit()
which one can really help and where?What if security Manager comes into picture?
class ExitCatchingSecurityManager extends SecurityManager
public void checkExit(int status)
Process.terminateProcessWithThreadGroup(getThreadGroup());
throw new SecurityException();
What if an application calls System.exit()?
We still have one big hole in our multiprocess library. If any application calls System.exit(), the JVM terminates, and all the pseudo-processes will be destroyed with no warning. Fortunately, Java's design once again comes to our aid. Any call to System.exit() is first checked by the SecurityManager to see if the application has permission to terminate the JVM. We can install our own SecurityManager to catch the System.exit() call, disallow it, and terminate the pseudo-process instead. The SecurityManager is actually quite simple to define:
class ExitCatchingSecurityManager extends SecurityManager
public void checkExit(int status)
Process.terminateProcessWithThreadGroup(getThreadGroup());
throw new SecurityException();
In addition, the SecurityManager should define all other checks so that they do not block pseudo-processes from running. A simple null call for all check* methods will work. We install our own SecurityManager by calling System.setSecurityManager(), i.e., by adding the following line near the startup of the multiprocess library:
System.setSecurityManager(new ExitCatchingSecurityManager());
The Process.terminateProcessWithThreadGroup() method is simple to define, by holding a collection of Process objects in the Process class, searching the collection to find the Process with the identical ThreadGroup, then terminating that Process. -
Can't throw exception inside try block!
Hi,
I'm having a problem trying to throw an error inside a try block.
To illustrate:
public class TestException {
public TestException() {
try {
int ret = foo();
System.out.println("ret is " + ret);
} catch (Exception ex) {
System.out.println("exception caught");
public int foo() throws Exception {
int ret = 0;
try {
throw new Exception("test exception");
} finally {
return ret;
public static void main(String[] args) {
new TestException();
If I run this the only output is "ret is 0" - I do not catch the thrown exception! What am I doing wrong?
Any and all help will be very gratefully received.
Thanks.I need to correct myself: I've re-read the spec, and actually the behaviour is conformant with the JLS: JLS says that the return statement completes abruptly, and an abrupt return in a finally block that didn't have a (applicable or any) catch block will result in the original exception being 'forgotten'.
Very unintuitive, but as-spec'ed -
Return statement and Try Catch problem
Hi!!
I've got the next code:
public ResultSet DBSelectTeam(String query) {
try {
Statement s = con.createStatement();
ResultSet rs = s.executeQuery(query);
return rs;
} catch (Exception err) {
JOptionPane.showMessageDialog(null, "ERROR: " + err);
But I need a return statement in the catch-block, but I don't know what's the best option.
Help...
Many thanks.The error message is: "missing return statement", Yes, I know.
You have to either return from the catch statement, or throw from the catch statement, or return or throw after the catch statement.
The only ways your method is allowed to complete is by returning a value or throwing an exception. As it stands, if an exception is thrown, you catch it, but then you don't throw anything and you don't return a value.
So, like I said: What would you return from within or after catch? There's no good value to return. The only remotely reasonable choice would be null, but that sucks because now the caller has to explicitly check for it.
So we conclude that catch shouldn't return anything. So catch must throw something. But what? You could wrap the SQLE in your own exception, but since the caller is dealing with JDBC constructs anyway (he has to handle the RS and close it and the Statement), there's no point in abstracting JDBC away. Plus he has to deal with SQLE anyway in his use of the RS and Statement. So you might as well just throw SQLE.
So since you're going to just throw SQLE anyway, just get rid of the try/catch altogether and declare your method throws SQLException -
Return statement in exception and consequences
Hi,
Can any one give me the explanation for my doubt?
Case 1:
I am having some code throwing some exception lets say arithematic exception in my try block.
I caught it in the catch block and at last I am having one finally?
as per normal order try block next catch block and at last finally will execute.
I execute the above code by putting a return statement inside catch block.I got the same order of execution irrespective of return statement inside catch?
What is the significance of return inside catch?
Case 2:
Lets take the scenario.
class MyException
public static void main(String[] args)
int i=1,j=0;
try
try
System.out.println("the value is: "+(i/j));
System.out.println("Inside try block");
catch(ArithmeticException e)
System.out.println("hi in ame");
//return;
finally
System.out.println("inner finally");
System.out.println("outer try");
catch(Exception e)
e.printStackTrace();
System.out.println("in exception");
finally
System.out.println("plz wait");
If return statement is there inside the inner try and catch the code out of inside outer try not getting executed Why So?
Any clarifications?
Thanking you,
Murthy.First, please format your code as per http://forum.java.sun.com/features.jsp#Formatting
I'm not sure what part you don't understand.
. public static void main(String[] args) {
. try {
. try {
. throw new ArithmeticException();
. System.out.println("Inside try block"); // #1
. catch(ArithmeticException e) {
. System.out.println("hi in ame"); // #2
. return;
. finally {
. System.out.println("inner finally"); // #3
. System.out.println("outer try"); // #4
. catch(Exception e) {
. System.out.println("in exception"); // #5
. finally {
. System.out.println("plz wait"); // #6
. }#1 -- You won't get here because you throw AME.
#2 -- You will get here because you caught the AME you just threw.
#3 -- You will get here because it's a finally
#4 -- You won't get here. I think that this is what you're asking about: Why don't we get here? Because we've already done 'return' and this line is NOT inside a finally. The only things that can get executed after a return are finally blocks.
#5 -- You won't get here because you already caught the AME and didn't rethrow it or any other exception.
#6 -- You will get here because it's a finally.
Once you do a return, the only code you can execute before exiting the method are finally blocks. First the one corresponding to the try/cathc block where your return is, then the finally for the try/catch that encloses that one, and so on outward. The code between one finally and the next (#4 here) is NOT executed.
If you still have a question, please try to clarify exactly what behavior you don't understand.
Don't return from inside t/c/f. -
Doubts reg try block and return statements
hi
public int test()
try
System.out.println("hi");
return 1;
catch(Exception e)
System.out.println("err");
return 2;
finally
System.out.println("final");
return 3;
//System.out.println("after");
//return 4;
when i call this function, it will printing 3... why ??
and also compilation error is coming when i put return statement after final block.. why is it so??but if commented the return statements in catcch and finally then it iam not getting any compilation error.
public int test()
try
System.out.println("hi");
return 1;
catch(Exception e)
System.out.println("err");
// return 2;
finally
System.out.println("final");
// return 3;
System.out.println("after");
return 4;
and iam just learning ..... regarding return and try block -
Txt file read in- StringTokenizer- Try Block Catch for errors
Hello
So I am having a few issues with a school project. First is with my ReadWithScanner. It does not read in the file giving me a NullPointerException error on the line <Scanner in = new>. I have tried a few other read in files and they do not seem to be working.
I am also stuck on the logic on the try block catch statement. How does a person set up a �custom� try block that looks for errors like the ones below? I have attempted to start in the commented code.
The text file has to read in 1000 individual lines of code and are separated by �;� and should be separated into tokens with the StringTokenizer class what I attempted to do below also. Both are mere attempts and need help�
This is some what of the logic I thought of doing
1.Read the first line in first with the scanner class
2.use delimiter separated by �;�
3.Tokenizer the line into separate tokens- invoiceCode, fName, lName�
4.Check classes- check Name, check Date, checkPrice, checkPrice, checkGenre, checkShippingDate invoiceCode = "Error Code" checkInvoiceCode(String invoiceCode)checkName(String name), checkPrice(String price), checkGenre(String genre)
5.Apply the regular expressions to each try block statement
a.Assign a letter to each error for example if invoice was to short it would be assigned a letter A
b.If invoice does have the right characters it would be assigned B
c.If name has to few words it would be assigned D
d.�
This is an example of a good field from the text file
XYG726;Smith,Mr. John M.;29.96;comedy;101008;100604
Not so good line
Lu15;Will, Mark;50.00;Science;030305;030807
The file should then be printed out in the program not to a text file. It only needs to print the invoice number and error code letter assignment.
If you have any questions feel free to let me know. Thanks for all or any help you have to offer.
Invoice
Three upper case letters followed by three digits
Regular Expression "[A-Z]{3}[0-9]{3}"
Customer Name
Should be in the form: last name followed by a <,> optional title (Mrs. Mrs�) then first name optional middle initial Titles must be
So regular expression something like �[a-z][A-Z]+([A-Z]{1}?[a-z][./})+[a-z][A-Z]�
Sale Price
Two decimal digits to the left of the decimal point. The price should not have a leading zero.
Regular Expression [0-9]{2}*./[0-9]
Genre
The genre should only contain lowercase letters. Regular expression �[a-z]�
ShipDate and Order Date-
Must be standard dates- MMDDYY. The order date and shipping date has to be after today�s date. Regular expression �[0-9]{2}+[0-9]{2}+[0-9]{2}�
package Project3;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import java.util.Scanner;
public class ReadWithScanner {
private final File fFile;
public static void main (String args[]){
Scanner in = new Scanner(new File("e:\\work_space_java\\Project\\Package3\\movie.txt"));
Scanner.processLineByLine();
public ReadWithScanner(String aFileName){
fFile = new File(aFileName);
public final void processLineByLine(){
try {
//use a Scanner to get each line
Scanner scanner = new Scanner(fFile);
while ( scanner.hasNextLine() ){
processLine( scanner.nextLine() );
scanner.close();
catch (IOException ex){
protected void processLine(String aLine){
//use a second scanner again to raed the content of each line
Scanner scanner = new Scanner(aLine);
scanner.useDelimiter(";");
if (scanner.hasNext() ){
//read each file?
String name = scanner.next();
String value = scanner.next();
else {
scanner.close();
//Token Names that are seperated
StringTokenizer st;
String invoiceCode = st.nextToken();
String fname = st.nextToken();
String lname = st.nextToken();
String price = st.nextToken();
String genre = st.nextToken();
String orderDate = st.nextToken();
String shipDate = st.nextToken();
String invoiceCode;
invoiceCode = "A" checkInvoiceCode(String invoiceCode);
Pattern p = Pattern.compile("[a-z]{6}[A-Z]{6}[0-9]{6}");
Matcher m = p.matcher(invoiceCode);
p.matcher(invoiceCode);
if(m.matches()) {
System.out.println(invoiceCode);
else {
System.out.println ("A");
try
invoiceCode = Integer.parseInt(String);
catch (NumberFormatException e)
{ System.out.println ("B"); System.exit(1); }
*/I have made a quite a few updates to my code. Please look it over again. I have also made many comments to help with the logic. Once again if you have any questions please feel free to ask. Sorry about not using the tags before- I was no aware of them. Thanks for the advice sabre150.
package Project3;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import java.util.Scanner;
public class ReadWithScanner {
private final File fFile;
public static void main (String args[]){
//read in text file from directory currently it can not read the file
Scanner in = new Scanner(new File("e:\\work_space_java\\Project\\Package3\\movie.txt"));
//Scans each line of the text in
Scanner.processLineByLine();
//assigns new file name to file
public ReadWithScanner(String aFileName){
fFile = new File(aFileName);
public final void processLineByLine(){
try {
//use a Scanner to get each line from the processLineByLine
Scanner scanner = new Scanner(fFile);
while ( scanner.hasNextLine() ){
processLine( scanner.nextLine() );
scanner.close();
catch (IOException ex){
protected void processLine(String aLine){
//use a second scanner again to read the content of each line
//delmiter should then break each line in the text file into seperate "tokens"
Scanner scanner = new Scanner(aLine);
scanner.useDelimiter(";");
if (scanner.hasNext() ){
//reads each line from scanner
String name = scanner.next();
else {
scanner.close();
/*Convert Tokens from Scanner into String Tokenizer with assigment to each variable
* I am missing something
* Need to convert each line read from the scanner (name variable) to the String
* Tokenizer class
//Tokens names now assigned a varaible
StringTokenizer st;
String invoice = st.nextToken();
String name = st.nextToken();
String price = st.nextToken();
String genre = st.nextToken();
String orderDate = st.nextToken();
String shipDate = st.nextToken();
/*If statments (Try Block Statements?) with Regular Expressions
* This is where I have the most issues on how to set up
* "custom" try and block errors trying to match what I have
* in the regular expressions.
* I believe try and catch statements
* make this easier but I have used 'match' and 'pattern' with if
* statments. If try block statements are easier please show!
* Regular Expressions may not be correct either
invoice = checkInvoiceCode(invoice);
//Defined cerita for Inovice are:
//Error A = Invoice code is too short
//Error B = Invoice code does not have the right characters
//Error C = Invoice code digits are all zero
//Checks for error A
//Has at least six characters
Pattern invoiceShort = Pattern.compile("{6}");
Matcher shortInvoice = invoiceShort.matcher(invoice);
p.matcher(invoiceCode);
if(m.matches()) {
System.out.println(invoice);
else {
System.out.println ("A");
//Checks for error B
//3 Upper Case Letters followed by three numbers,
Pattern rightChar = Pattern.compile("[A-Z]{3}[0-9]^0{3}");
Matcher charRight = rightChar.matcher(invoice);
p.matcher(invoiceCode);
if(m.matches()) {
System.out.println(invoice);
else {
System.out.println ("B");
//Checks for error C
//Where the last three digits are not all zeros
Pattern notZero = Pattern.compile("*{3}^0{3}");
Matcher ZeroNot = notZero.matcher(invoice);
p.matcher(invoiceCode);
if(m.matches()) {
System.out.println(invoice);
else {
System.out.println ("C");
//name = checkFullName(name);
//Error D = Name field has fewer than two words
//Error E = Name field has more than four words
//Error F = Name field has no comma
//Error G = Name field has a bad title
//Error H = Name field has a bad initial
/*Have a lot more to do...
* Still need to go through the same if statement or Try Block statements with this data:
* String fname = st.nextToken();
String lname = st.nextToken();
String price = st.nextToken();
String genre = st.nextToken();
String orderDate = st.nextToken();
String shipDate = st.nextToken();
* But for now I would like to see an example of an if statement I could use
* (if mine is even right) or catch statement- the rest of the project we look
* for similar certia as defined in the reg exp for invoice
/*Writes to Report in the Console
* Prints data into two columns:
* Invoice Code and Error Type
//Prints both column Headings
private void columnHeadings ()
System.out.println (padL("",5) +
padL("Invoice",20) +padL("",20)+
padL("Error Code",40));
//movie is the name of the text file
private void printMovie(Movie aReport) {
System.out.println(aReport.getInvoiceCode()+"\t"+
aReport.getErrorType()+"\t");
*This method pads the string start to the length newLength leaving the
*string left justified and returning the result.
private String padL (String start, int newLength)
String result = new String (start);
while (result.length() <= newLength) result += " ";
return result;
} // end padL
* This method pads the string start to the length newLength leaving the
* string right justified and returning the result.
private String padR (String start, int newLength)
String result = new String (start);
while (result.length() <= newLength) result = " " + result;
return result;
// end padRThanks a lot. -
Return statement in a try catch block
Hi friends
Take a look in the code bellow
try
return (true)
finally
System.out.println("blabla");
If nothing strange hapens in the try code, the return statement will be achieved. In this case, what will hapen ? The code in the finally block will be executed ??
thanksIf nothing strange hapens in the try code, the return
statement will be achieved. In this case, what will
hapen ? The code in the finally block will be executed
??Yes. Hence the word "finally". -
Return statement at the end of try or after catch blocks
Hi
Can anyone tell me which is the better practice - to put the return statement at the end of try block or after all the catch blocks ie at the end of method.
Eg
Method A()
String str;
try{
str= [some code]
return str
catch(Exception e)
System.out.println("Exception");
} // end of method
OR
Method B()
String str;
try{
str= [some code]
}catch(Exception e)
System.out.println("Exception");
return str
} // end of methodI always try to work with only one exit point for each method.
For readability I always put the return statement as close to the end of the method as possible.
In this particular question,
I think you should put the return at the end of the method (for readability, since this is what you are
familiar with), but when I have a try-catch clause, I usually have an unrecoverable error and
should throw this further down the tree, so it usually becomes
try{
return
}catch(...){
// write out some logging information
rethrow exception or throw another exception
}I think you should NEVER reflect the occurence of an error in the return-value of the
method when an unrecoverable exception occurs. Just rethrow this exception or throw another method.
Other methods look like
Object result = new...
return result;As for the specific case of a repetitive if-case:
This is possible in two versions:
With one return and a result-object
Object result = new ...
if(..)
result = ...
else if(..)
result = ...
return result;With every time a return
if(...)
return ...;
else if(...)
return ...;For me the above two possibilities make no difference,
but I find the second version (which I hated when I began programming)
to be somewhat more of a (self-made) standard nowadays.
But I do not think this particular case makes much of a difference.
kind regards, -
Return statement should put beyond try/catch clause??
The return statement should put beyond the try/catch clause, is that correct? Well,
I tried to put inside the try block, but it will have compile error though.
public String getValue()
String value;
try
catch(...)
return value;
please advise. thanks!!When a method returns a value, you must make sure that even if an exception is thrown and caught a value will be returned (or just throw the exception out of the method).
You can put a return clause as the last thing in the try block and another return clause after the catch block (this is where we go if we catch an exception so you probably want to return null). -
hi there
if a method needs to return a value, but there maybe an exception caught in a try block, where should i place the return statement, outside the try bccok or inside
code...
public String readFrom()
String temp;
try
temp = br.readLine();
catch (IOException ex)
System.out.println(ex);
return temp;
}It should be coded as you have it. There should (ideally)
be only one exit point from a method. If an exception is
thrown, the code in the catch block will be executed and
processing will continue. You can use the catch block
to set the value of the variable that is being returned to
indicate that an error has occurred. In your example,
you could set the String temp to null.
Mark
Maybe you are looking for
-
Power button issue Mac Pro 2.66
Mac Pro 2.66 is connected to a power strip I now notice that I do not have to press the power button to boot this Mac up. To boot it I need to just turn the power strip on WITHOUT pressing the power button and it boots right up. Only occasionally whe
-
How do you get your songs from your ipod to your computer?
can anyone tell me how to get your songs from your ipod to your computer?
-
Since I upgraded to Mavericks, Time Machine won't work. It took a whole day to backup about 16 GB over a wired ethernet connection. At 29 GB, my Mac crashed; totally unresponsive; it wouldn't even respond to a ping from another computer. I've tried t
-
CS2 iIlustrator will not start up
Hi All, my co-designer has recently got a problem with CS2 illustrator. It will not get past the splash screen when she starts it. It stops after initialising appears in text on the splash screen. We have tried switching off Suitcase Fusion before
-
Hi, I have to create report like the followi Tr.No Item.No Itemvalue TotalTransactionValue 1 1 100 300 1