Help regarding try catch!
In the following code, when the exception occurs at b, the control goes to the catch block! however, though the values for c, d are perfect, they are never reached!
Is there anyway to make the control return to where the exception was thrown & continue from there?
int a=0,b=0,c=0,d=0,
try {
a = Integer.parseInt("11");
b = Integer.parseInt("aa");
c = Integer.parseInt("33");
d = Integer.parseInt("44");
} catch(Exception ex) {
System.out.println("Except occured: " + ex);
}
No.
If you want that other code to execute it would need a seperate try/catch block OR to go in the finally block. Whatever you feel.
Similar Messages
-
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. -
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. -
im experiment trying to make a calculator applet and have the usual:
plus
minus
multiply
divide
etc
which i have enclosed the action to these buttons in a try catch to ensure data is entered and it is correct. I have also 4 special buttons that i want to add but dont need any data to be entered so i have placed them outside the {} of the try catch but when i click on buttons it seems they are still being caught in the try catch
any help would be most appricatedWell,
Its very difficult to say why your unguarded code is behaving like the guarded section as if it is inside try block.
better post ur code along with your query, it will help analyze the problem better.
Kind Regards
Rahul Bajaj -
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. -
Hi,
i do method that get input and return table and i wont to use try & catch if the table i receive is empty how i can do that exception library?
Regardsif within ur method no exception is raised then no need to use try..catch..entry block.
After the method call u can directly check the contents of the return table. If it contains value then do further processing otherwise do the error handling.
Regards,
Joy. -
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. -
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);
} -
OutOfMemory Exceptions on Servlets, Try-Catch unable to help
Hi, I'm playing with Java servlets right now and I seem to be getting some OutOfMemory errors. The weird thing is that even though I had identify the souce of error and tried to enclose it with a try-catch, the exception still occurs. Why is that so?
OutOfMemoryError is actually a java.lang.Error, not a RuntimeException. So if you use a try/catch like this
try {
// stuff
} catch (Exception e) {..}Errors will fall through, since Error is not a subtype of Exception. (Check the API.)
You can catch it by catching Error or Throwable, like this:
try {
// stuff
} catch (Error e) { // this is rarely a good idea
}But you normally wouldn't want to do this. When there's no memory left, there's not a whole lot you can do about it, and most of the code you might want to put inside the catch block will merely throw another OutOfMemoryError.
As voronetskyy said, you're either creating too many (or too large) objects (typically in an endless loop), or you have specified too little memory for your application. -
Dear all,
Can any body clear me what is code for try catch in SAP 4.6C? I tried the below code but the object type is doesn't exist. ( cx_root or x_sy_native_sql_error)
DATA: exc_ref TYPE REF TO cx_root, " cx_sy_native_sql_error,
error_text TYPE string.
LOOP AT it_sqlupdate.
try.
EXEC SQL.
insert into TBLSVBALSAP
( CoCode, SAPDocNo, PostDate, DocHdrTxt, GLAccount,
Amount, Text, RevDoc, CreationDate, CreationTime ) values
( :it_sqlupdate-c_code, :it_sqlupdate-sap_docno, :it_sqlupdate-p_date,
:it_sqlupdate-h_text, :it_sqlupdate-gl_acc, :it_sqlupdate-amt,
:it_sqlupdate-i_text, :it_sqlupdate-r_docno, :it_sqlupdate-c_date,
:it_sqlupdate-c_time )
ENDEXEC.
catch cx_sy_native_sql_error into exc_ref.
error_text = exc_ref->get_text( ).
MESSAGE error_text type 'I'.
endtry.
ENDLOOP.
Thanks.Hi,
I think, TRY CATCH Exception concept was not there in 4.6C, alternatively you can try with
CATCH SYSTEM-EXCEPTIONS.
Check the link below
http://help.sap.com/abapdocu/en/ABAPCATCH_SYS.htm
regards
Mahesh -
Help Regarding Emoticons....('',) ??
Hello to all experts,
I need some help regarding my Chat program...
Can anybody should tell me how to access Emoticons images from a particular destination or source using a java code....
Or Is there any way to access that emoticons using XML file...so that it will then read from a Java code....??
XML file look like as :-
<root>
<img1>path of the image or emoticon</img1>
<img2>......................... ........................</img2>
</root>By using above file i will read emoticons using Java code....??
Is there any function , Method or a sample code to do that job...
Thanks in Advance.....Thanks DrClap....
One More thing I want to knw from you.....
Actually Other then this Emoticons help....
I had given a post in Java Help System for getting help regarding How to open a HelpSet file from a java code By just putting JH.Jar in my Lib path.
I am using the following program to do so...
public class JavaHelpDemo extends JFrame
private HelpBroker someHelpBroker;
public JavaHelpDemo()
HelpSet hs;
try
File f = new File("Master.hs");
URL url = f.toURL();
hs = new HelpSet (null, url);
HelpBroker hb = hs.createHelpBroker();
new CSH.DisplayHelpFromSource(hb);
hb.setDisplayed(true);
catch (Exception a)
System.out.println("Error is here");
System.out.print(a);
// constructor
public static void main(String[] args)
JavaHelpDemo javaHelpDemo1 = new JavaHelpDemo();
}//classActually my this program is running well and I m getting my helpset only when i insert all my files with htmls in my source path.....
I hav created a Jar or all these files and named it Help.jar
is there any way just to call that helpset using this jar without giving all files into source path.....
Regards,
Daman. -
Need help regarding Java decoding of IMAP attachment (IOStream related ques
Hi ,
I need some help regarding the processing of an IMAP attachment , It is a basic IOStream related question I guess.
I have some attachment to a mail , I try to fetch it using javamail and read the content and write it to a file , I was able to do it successfully when I was using stream.read( tempBuffer) function but when I started using stream.read( tempBuffer, 0, m_maxDataSize ); it is giving me following exception
java.io.IOException: Error in encoded stream: needed at least 2 valid base64 characters, but only got 1 before padding character (=), the 10 most recent characters were: "/59PT/eXQ="
at com.sun.mail.util.BASE64DecoderStream.decode(BASE64DecoderStream.java:259)
at com.sun.mail.util.BASE64DecoderStream.read(BASE64DecoderStream.java:148)
***Here is the snippet of code that is running this:***
m_contentObj = m_message.getContent();
if(m_contentObj instanceof InputStream)
System.out.println(" Content is type of InputStream");
InputStream stream = (InputStream) m_contentObj;
byte[] tempBuffer = new byte[m_maxDataSize];
stream.skip( m_currPos );
int bytesRead=stream.read( tempBuffer, 0, m_maxDataSize );
System.out.println(" Read the following no of bytes from the Object::"+bytesRead);
m_currPos+= bytesRead;
Please suggest what to do.
Thanks & Regards
SaurabhBUMP, just incase its been missed by a new board member
-
Can't find class because of try catch block ?!
Hello,
I'm using the JNI to use a java library from my c++ code.
JNI can't find the "Comverse10" class below, but when i put the try catch block in createMessage in comment, FindClass succeeds ?!
Unfortunatly i need the code inside the try block ;-)
I tried a few things, but none of them worked:
- let createMessage throw the exception (public void createMessage throws ElementAlreadyExistsException ), so there isn't a try catch block in createMessage => result: the same
- make a "wrapper" class Comverse that has a Comverse10 object as attribute and just calls the corresponding Comverse10.function. Result: Comvers could be found, but not constructed (NewObject failed).
Can someone tell me what is going on ?!
Thank you,
Pieter.
//Comverse10 class
public class Comverse10 {
MultimediaMessage message;
/** Creates a new instance of Comverse10 */
public Comverse10() {
public void createMessage() {
TextMediaElement text1 = new TextMediaElement("Pieter");
text1.setColor(Color.blue);
SimpleSlide slide1 = new SimpleSlide();
//if i put this try catch block in comment, it works ?!
try{
slide1.add(text1);
catch(com.comverse.mms.mmspade.api.ElementAlreadyExistsException e){}
MessageContent content = new MessageContent();
content.addSlide(slide1);
this.message = new MultimediaMessage();
message.setContent(content);
message.setSubject("Mijn subjectje");
for those of you who are intersted: here's my C++ code:
//creation of JVM
HRESULT Java::CreateJavaVMdll()
HRESULT HRv = S_OK;
char classpath[1024];
jint res;
if(blog) this->oDebugLog->Printf("CreateJavaVMdll()");
strcpy(classpath,"-Djava.class.path="); /*This tells jvm that it is getting the class path*/
strcat(classpath,getenv("PATH"));
strcat(classpath,";D:\\Projects\\RingRing\\MMSComposer;C:\\Progra~1\\j2sdk1~1.1_0\\lib"); //;C:\\Comverse\\MMS_SDK\\SDK\\lib\\mail.jar;C:\\Comverse\\MMS_SDK\\SDK\\lib\\activation.jar;C:\\Comverse\\MMS_SDK\\SDK\\lib\\mmspade.jar
//------Set Options for virtual machine
options[0].optionString = "-Djava.compiler=NONE"; //JIT compiler
options[1].optionString = classpath; //CLASSPATH
//------Set argument structure components
vm_args.options = options;
vm_args.nOptions = 2;
vm_args.ignoreUnrecognized = JNI_TRUE;
vm_args.version = JNI_VERSION_1_4;
/* Win32 version */
HINSTANCE hVM = LoadLibrary("C:\\Program Files\\j2sdk1.4.1_01\\jre\\bin\\client\\jvm.dll");
if (hVM == NULL){
if(blog) oDebugLog->Printf("Can't load jvm.dll");
return E_FAIL;
if(blog) oDebugLog->Printf("jvm.dll loaded\n");
LPFNDLLFUNC1 func = (LPFNDLLFUNC1)GetProcAddress(hVM, "JNI_CreateJavaVM");
if(!func){
if(blog) oDebugLog->Printf("Can't get ProcAddress of JNI_CreateJavaVM");
FreeLibrary(hVM); hVM = NULL;
return E_FAIL;
if(blog) oDebugLog->Printf("ProcAddress found");
res = func(&jvm,(void**)&env,&vm_args);
if (res < 0) {
if(blog) oDebugLog->Printf("Can't create JVM with JNI_CreateJavaVM %d\n",res);
return E_FAIL;
if(blog) oDebugLog->Printf("JVM created");
return HRv;
//finding Comverse10 class:
HRESULT CALLAS MMSComposer::InitializeJNI(void)
HRESULT HRv=E_FAIL;
DWORD T=0;
try
if(blog) oDebugLog->Printf("\nInitializeJNI()");
bJVM = FALSE;
jni = new Java(oDebugLog);
if(jni->CreateJavaVMdll()!=S_OK){
if(blog) oDebugLog->Printf("CreateJavaVMdll() failed");
return HRv;
jclass jcls = jni->env->FindClass("Comverse10");
if (jcls == 0) {
if(blog) oDebugLog->Printf("Can't find Comverse10 class");
jclass jcls2 = jni->env->FindClass("test");
if (jcls2 == 0) {
if(blog) oDebugLog->Printf("Can't find test class");
return HRv;
if(blog) oDebugLog->Printf("test class found %08x",jcls2);
return HRv;
if(blog) oDebugLog->Printf("Comverse10 class found %08x",jcls);
jmethodID mid = jni->env->GetMethodID(jcls , "<init>", "()V");
if (mid == 0) {
if(blog) oDebugLog->Printf("Can't find Comverse10() constructor");
return HRv;
if(blog) oDebugLog->Printf("Comverse10() constructor found");
jobject jobj = jni->env->NewObject(jcls,mid);
if(jobj==0)
if(blog) oDebugLog->Printf("Can't construct a Comverse10 object");
return HRv;
if(blog) oDebugLog->Printf("Comverse10 object constucted");
//Create Global reference, so java garbage collector won't delete it
jni->jobj_comv = jni->env->NewGlobalRef(jobj);
if(jni->jobj_comv==0)
if(blog) oDebugLog->Printf("Can't create global reference to Comverse10 object");
return HRv;
if(blog) oDebugLog->Printf("global reference to Comverse10 object %08x created",jni->jobj_comv);
bJVM=TRUE;
HRv=S_OK;
} catch( IDB * bgError ) { throw bgError->ErrorTrace("InitializeJNI::~InitializeJNI",HRv, 0, T); }
catch(...) { throw IDB::NewErrorTrace("InitializeJNI::~InitializeJNI",HRv, 0, T ); }
return HRv;>
I would guess that the real problem is that that the
exception you are catching is not in the class path
that you are defining.Thanks jschell, that was indeed the case.
I don't have the docs, but I would guess that
FindClass() only returns null if an exception is
thrown. And you are not checking for the exception.
Which would tell you the problem.Ok, i'll remember that. But what with exceptions thrown in my java code, the documents say
// jthrowable ExceptionOccurred(JNIEnv *env);
// Determines if an exception is being thrown. The exception stays being thrown until either the native code calls ExceptionClear(), or the Java code handles the exception
so, what if the java code throws an exception and catches it, will i be able to see that in my c++ code with ExceptionOccurred ?
or
should the java method be declared to throw the exception (and not catch it inside the method)
Again, thank you for your help, it's greatly appreciated ! -
Can we have try/catch in a static block in a class?
hi All
i have a question about put a try/catch block in a static block in a class to catch exceptions that maybe thrown from using System.xxxx(). in my custom class, i have a static block to initialize some variables using System.xxx(). in case of any error/exception, i need to be able to catch it and let the caller know about it. i tried to put a try/catch block in the static block, and tried to rethrow the exception. but it is not allowed, how would i handle situation like this? thanks for your help and advise in advance.You could just swallow the exception inside try/catch
block, and instead of throwing it out, just set a
static variable to allow checking from outside
whether the initialization succeeded, or check within
the constructor / methods of this class for
successful initialization, and throw the exception
then. You could even save that exception in a static
variable for later.Ouch, ouch, you're hurting my brain. This would allow someone to ignore a (presumably) fatal error. Throw a RuntimeException as indicated. You can wrap a checked exception in an unchecked one if need be.
Maybe you are looking for
-
i have my mac book frozen when i put os disc in and pressed restart it went to restart apple logo cam on screen and now it has stayed like that for 24 hours i have not been able to eject disc or response fromkeypad please help
-
WPC - highlighting the link of the current page in the link list
Hi, is there any way to highlight a link in my linklist if it's the link to the page i am currently visiting? That would make it possible for me to customize the link list form and change it into some kind of "tab"-list form where the current tab is
-
I just got virtual pc with windows xp professional edition (yay) and it is working nicely. i was wondering if anyone knew enough about it to walk me through the steps to join a network, (airport, ethernet, ect.) that is non-encrypted and does not req
-
Hi this is kamesh, I received one dump file(.dmp) from the client(UK) at the time of export that file they were used Oraacle 8.1.7 Version.That file in ASCII mode. How can i import that .dmp file in Oracle 10.2 Version. At the time of Export the data
-
Crosstab - Different Value Different Color
Post Author: tomahawk CA Forum: Crystal Reports I have a cross tab which has 3 columns (priority) The value of the column (Priority) comes from the database which can be either Critical, Major or Minor or all 3. For each priority, there is a value in