FileNotFound Exception - try,catch
Hi,
I am having the following problem:
Original working code:
public String[] SomeMethod(){
filename = dirname + ...blah blah blah..;
return filename;
New code:
public String[] SomeMethod(){
filename = dirname + ...blah blah blah..;
try{
Here I am opening the file with name filename and I am appending to it using another file. Also I am closing those files...
}catch(IOException e){
System.out.println("xyz.....blah blah");
return filename;
The only thing I added was the try block. And now it is not able to access that file which is being returned by the method. When I checked the file, it is getting appended. So, the code I added in the try block is working, but somehow the file is not accessible after the method gets executed. Any help? Any ideas?
Hi,
I am posting the method so that it will be more clear. I did not post previously bcos people might get confused seeing what the method does.
public String[] getDataSources()
String datadir = (String)args.get("datadir");
if(datadir == null)
return super.getDataSources();
String fileNames[] = new String[1];
SimpleDateFormat fileDF = new SimpleDateFormat("MMMdd");
Calendar feedDate = (Calendar)fireDate.clone();
String dateOffsetStr = (String)args.get("dateoffset");
if(dateOffsetStr != null)
int dateOffset = new Integer(dateOffsetStr).intValue();
feedDate.add(Calendar.DATE, dateOffset);
Calendar tmpDate = (Calendar)feedDate.clone();
tmpDate.add(Calendar.DATE, -6);
fileNames[0] = "'" + datadir + File.separatorChar + "''FEED." + fileDF.format(tmpDate.getTime()).toUpperCase() + ".";
tmpDate.add(Calendar.DATE, 6);
fileNames[0] += fileDF.format(tmpDate.getTime()).toUpperCase() + "'''";
/****** NOTE: The above fileName gives something like: '/path/to/file/''filename''' - please don't worry about it. That is correct... this format is sent to another file where it is actually parsed to get the correct file name and blah blah blah... To tell you in short this code works fine without the block of code I added.. which is shown below: ********/
//****************** New code ********************
String ods_file_name,op_file_name;
Calendar fileDate = (Calendar)feedDate.clone();
//File1 Name format Ex: 'FEED.MAY31.JUN06'
//File2 Name format Ex: 'FEED_ODS.MAY31.JUN06'
fileDate.add(Calendar.DATE, -6);
op_file_name = datadir + File.separatorChar + "'FEED." + fileDF.format(fileDate.getTime()).toUpperCase() + ".";
ods_file_name = datadir + File.separatorChar + "'FEED_ODS." + fileDF.format(fileDate.getTime()).toUpperCase() + ".";
fileDate.add(Calendar.DATE, 6);
op_file_name += fileDF.format(fileDate.getTime()).toUpperCase() + "'";
ods_file_name += fileDF.format(fileDate.getTime()).toUpperCase() + "'";
try{
File ods_file = new File(ods_file_name);
int len_ods_file = (int)ods_file.length();
byte[ ] buffer = new byte[len_ods_file];
FileInputStream ods_inp = new FileInputStream(ods_file_name);
ods_inp.read(buffer, 0, len_ods_file);
ods_inp.close();
ods_file = null;
FileOutputStream out = new FileOutputStream(op_file_name,true);
out.write(buffer);
out.close();
return fileNames;
}catch(IOException e){
System.out.println("OP or ODS File not found");
// ************* New code end **********************
return fileNames;
}
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 -
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 -
IO or FileNotFound Exception catch does not work for getRequestDispatcher
Hi,
I am trying to catch IOException / FileNotFoundException in my servlet for the call to getRequestDispatcher().forward(request, response) and than throw user define exception from that catch. I am using JDeveloper 10.1.3. Some how the control is not going to catch block when the file does not exist to forward. But instead JDeveloper is throwing its own exception with error mesg
NOTIFICATION J2EE JSP0008 Unable to dispatch JSP Page : java.io.FileNotFoundException:
and browser shows standard 404 File Not Found error page. I would rather have want to display appropriate error page. Here is my code:
try
System.out.println("in try");
context.getRequestDispatcher("/" + currentScreen).forward(request, response);
System.out.println("after try");
catch(java.io.IOException fileNotFoundEx)
System.out.println("runtime exception");
logger.error(CLASS_OBJECT, "f n f "+RootException.getStackTraceString(fileNotFoundEx));
throw new RequestHandlerException("requestHandlerError", fileNotFoundEx);
Here is the output on console:
06/08/01 10:35:18 in try
2006-08-01 10:35:18.921 NOTIFICATION J2EE JSP0008 Unable to dispatch JSP Page : java.io.FileNotFoundException: F:\JavaProjects\WorkspaceDev\CorAssessment\web\jsp\assessment_multi_view1.jsp (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.io.FileInputStream.<init>(FileInputStream.java:66)
at oracle.jsp.provider.JspFilesystemResource.fromStream(JspFilesystemResource.java:150)
at oracle.jsp.parse.XMLUtil.getFromStream(XMLUtil.java:228)
at oracle.jsp.runtimev2.JspPageCompiler.compilePage(JspPageCompiler.java:341)
at oracle.jsp.runtimev2.JspPageInfo.compileAndLoad(JspPageInfo.java:610)
at oracle.jsp.runtimev2.JspPageTable.compileAndServe(JspPageTable.java:634)
at oracle.jsp.runtimev2.JspPageTable.service(JspPageTable.java:370)
at oracle.jsp.runtimev2.JspServlet.internalService(JspServlet.java:478)
at oracle.jsp.runtimev2.JspServlet.service(JspServlet.java:401)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:719)
at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:376)
at com.evermind.server.http.ServletRequestDispatcher.unprivileged_forward(ServletRequestDispatcher.java:270)
at com.evermind.server.http.ServletRequestDispatcher.access$100(ServletRequestDispatcher.java:42)
at com.evermind.server.http.ServletRequestDispatcher$2.oc4jRun(ServletRequestDispatcher.java:204)
at oracle.oc4j.security.OC4JSecurity.doPrivileged(OC4JSecurity.java:283)
at com.evermind.server.http.ServletRequestDispatcher.forward(ServletRequestDispatcher.java:209)
at com.nexcom.cor.manager.ViewManager.forwardToNextScreen(ViewManager.java:142)
at com.nexcom.cor.controller.FrontController.doProcess(FrontController.java:85)
at com.nexcom.cor.controller.FrontController.doGet(FrontController.java:59)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:743)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:719)
at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:376)
at com.evermind.server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:870)
at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:451)
at com.evermind.server.http.HttpRequestHandler.serveOneRequest(HttpRequestHandler.java:218)
at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:119)
at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:112)
at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260)
at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
at java.lang.Thread.run(Thread.java:534)
06/08/01 10:35:18 after try
It does not goto catch block and not printing message from System.out.You can map error codes to a specific jsp in your web.xml file, and add a parameter to the jsp that will display the message you intend to display back to the user.
Example:
<error-page>
<error-code>404</error-code>
<location>/index.html</location>
</error-page>
You can also trap specific exceptions by doing the following:
<error-page>
<exception-type> java.lang.Exception </exception-type>
<location>/ErrorPage.jsp</location>
</error-page> -
Doubt on try/catch exception object
why it is not advisable to catch type exception in try catch block. Its confusing me. If i catch exception object then it will show whatever exception occured.
btw, i was just go through duke stars how it works and saw this
http://developers.sun.com/forums/top_10.jsp
Congrats!Because there are many different kinds of Exception. If you have some specific local strategy for dealing with a particular excepion then you should be using a specific catch block.
If you don't then you should allow the expection to end the program, and ideally you should deal with all the expceptions in one top-level handler, so you should throw, rather than catch the exceptions in your methods. Often at the outer most level of the program or thread you will actually catch Throwable (not just Exception) to deal with any unanticipated problems in a general kind of way.
Also, you should be keeping track of what exceptions might be thrown, so that rather than using Exception in a throws clause or catch block, you should use the particular exceptions. Exceptions, generally, indicate a recoverable error that you really ought to be recovering from rather than just printing a stacktrace.
That's why exceptions are treated differently from runtime errors. -
Try/Catch Unknown Host Exception
I need to validate for an error of Unknown Host Exception, in case someone tries connected to a server that doesn't exist, or types the wrong host name, so i can display a message. how do I do that, with a try catch block.
I thought i would do:
try{
my code here such as...
DatagramSocket socket = new DatagramSocket();
// send request
InetAddress address = InetAddress.getByName(args[0]);
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);
...and so on, more code...
socket.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Unknown host " + args[0]);
}thanks, i also had to take out the e.printStackTrace(); and replace that with
my error message and System.exit(0); and I got what i needed! -
Hi there,
Was wondering if you could assist in me getting my head around try catch exception handling? I have this code:
JOptionPane.showMessageDialog(null, "A subject consists of term names and definitions.\nYou should indicate the size and name of the subject");
inputSubName = JOptionPane.showInputDialog(null, "Enter the Subject Name:");
inputSubSize = JOptionPane.showInputDialog(null, "Enter the Subject's Term Size:");
try {
size = Integer.parseInt(inputSubSize);
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "'" + inputSubSize + " is invalid " + " Please enter digits only");
inputSubSize = JOptionPane.showInputDialog(null, "Enter the Subject's Term Size:");
size = Integer.parseInt(inputSubSize);
//create a new Subject object and pass in its name and size
Subject sub = new Subject(inputSubName, size);
...My query is, if I catch an exception, how do I get the code to repeat the try again until the user inputs a correct data type? If the user above inputs something other than a number, it will catch it once and repeat the joptionpane inputbox, but if they do the same thing twice round - then the program bombs out. Is there a way i can get the code to retry the try until they input correctly?
Cheers.eg.
int size = 0;
while (true) {
try {
size = Integer.parseInt(inputSubSize);
break;
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "'" + inputSubSize
+ " is invalid " + " Please enter digits only");
inputSubSize = JOptionPane.showInputDialog(null,
"Enter the Subject's Term Size:");
} -
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. -
Does Labview have Try Catch exception handling?
1) Does Labview have Try Catch functions, exception handling?
2) Can Labview access a file or download a file using http or https?
3) How can labview read data from an ex ternal server http or https?
This is in labview 2009 or 2011Hi E,
1. you can chain together your VIs with the error wires, such that if an error occurs in one of them, none of the following VIs will execute. That's like throwing an exception - it interrupts the execution chain. You then "catch" that exception by putting an error handler wherever necessary, but not necessarily in every single VI.Hope You wouldn't put try..catch inside every single .NET function, instead you handle the exception at the level at which is most appropriate. Same thing can be done in LabVIEW.
Also see this.
2. The attached example downloads a picture with http "GET" command.
Dilbert.Main_LV71.vi 160 KB
3.see this thread:
http://forums.ni.com/t5/LabVIEW/Read-a-text-file-from-Labview-web-server-http/td-p/267434
Yes!!The same thing pointed out by nijims.
Thanks as kudos only -
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();
} -
Hello I am trying to parse an xml file chosen by the user. The file chosen is under:
wkdis3/home/bwe but everytime i got this exception:
ption caught: class java.io.FileNotFoundException
Datei AABC.XML ist nicht g�ltig.java.io.FileNotFoundException: \home\bwe\AABC.XML (Das System kann den angegebenen Pfad nicht finden)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:78)
at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:99)
at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:164)
at org.apache.xerces.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
at org.apache.xerces.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at ParseTest.<init>(ParseTest.java:51)
at ParseTest.main(ParseTest.java:105)
has anyone any idea baout that? and the main metode is so:
public static void main(String[] args) {
// Work with /Dir/File.txt on the system wkdis3.
AS400 system = new AS400("wkdis3");
IFSJavaFile dir = new IFSJavaFile(system, "/home/bwe");
JFileChooser chooser = new JFileChooser(dir, new IFSFileSystemView(system));
Frame parent = new Frame();
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
IFSJavaFile chosenFile = (IFSJavaFile)(chooser.getSelectedFile());
System.out.println("You selected the file named " +
chosenFile.getName());
String filename = chosenFile.getName()
try{
File file= chosenFile;
ParseTest xIncludeTest = new ParseTest(file);
}catch(Exception e) {
// System.out.println("Exception"+e+ "ist gefunden. /n ");
System.out.println("Exception caught: "+e.getClass());
System.out.println("Datei "+filename+" ist nicht g�ltig.");
e.printStackTrace();
}//ende catch
}//Ende if
} //ende main()
}/Thanks alot Mike ..The tips you gave were very helpful..I could solution using the Object IFSJavaFile, cause when i make :
IFSJavaFile chosenFile = (IFSJavaFile)(chooser.getSelectedFile());
II was getting only the path but not the system and when the systems are different(you were right XMl files were on OS400) then i got the FileNotFound Exception always.Down is the corrected main methode:
public static void main(String[] args) {
try{
// Work with /Dir/File.txt on the system wkdis3.
AS400 system = new AS400("wkdis3");
IFSJavaFile dir = new IFSJavaFile(system, "//wkdis3/ROOT/home/bwe/");
String directory0 = dir.getParent();
System.out.println ("Directory0: " + directory0);
String directory4=dir.getCanonicalPath();
System.out.println ("Canonicalpath-Directory4: " + directory4);
// IFSJavaFile dir = new IFSJavaFile( "\\wkdis3\ROOT\home\bwe");
JFileChooser chooser = new JFileChooser(dir, new IFSFileSystemView(system));
Frame parent = new Frame();
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
IFSJavaFile chosenFile = (IFSJavaFile)(chooser.getSelectedFile());
System.out.println("You selected the file named " +
chosenFile.getName());
String filename = chosenFile.getName();
IFSJavaFile file = new IFSJavaFile(system,directory4+filename);
ParseTest xIncludeTest = new ParseTest(file);
}//ende if
catch(Exception e) {
// System.out.println("Exception"+e+ "ist gefunden. /n ");
System.out.println("Exception caught: "+e.getClass());
// System.out.println("Datei "+filename+" ist nicht g�ltig.");
e.printStackTrace();
} -
Problem with reading from DAT file. FileNotFound exception
Can't seem to find the issue here. Two files, one (listOfHockeyPlayers) reads from a DAT file a list of players. The other (HockeyPlayer) has just the constructor to make a new hockey player from the read data.
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.awt.*;
import java.io.*;
public class ImportHockeyPlayers
private ArrayList<HockeyPlayer> listOfHockeyPlayers = new ArrayList<HockeyPlayer>();
public ImportHockeyPlayers(String fileName)
throws FileNotFoundException
try
Scanner scan = new Scanner(new File(fileName));
while (scan.hasNext())
//Uses all the parameters from the HockeyPlayer constructor
String firstName = scan.next();
String lastName = scan.next();
int num = scan.nextInt();
String country = scan.next();
int dob = scan.nextInt();
String hand = scan.next();
int playerGoals = scan.nextInt();
int playerAssists = scan.nextInt();
int playerPoints = playerGoals + playerAssists;
//listOfHockeyPlayers.add(new HockeyPlayer(scan.next(),scan.next(),scan.nextInt(),scan.next(),scan.nextInt(),scan.next(),
//scan.nextInt(),scan.nextInt(),scan.nextInt()));
catch(FileNotFoundException e)
throw new FileNotFoundException("File Not Found!");
public String toString()
String s = "";
for(int i = 0; i < listOfHockeyPlayers.size(); i++)
s += listOfHockeyPlayers.get(i);
return s;
public class HockeyPlayer
private String playerFirstName;
private String playerLastName;
private int playerNum;
private String playerCountry;
private int playerDOB;
private String playerHanded;
private int playerGoals;
private int playerAssists;
private int playerPoints;
public HockeyPlayer(String firstName, String lastName, int num, String country, int DOB,
String hand, int goals, int assists, int points)
this.playerFirstName = firstName;
this.playerLastName = lastName;
this.playerNum = num;
this.playerCountry = country;
this.playerDOB = DOB;
this.playerHanded = hand;
this.playerGoals = goals;
this.playerAssists = assists;
this.playerPoints = goals + assists;
DAT File
Wayne Gretzky 99 CAN 8/13/87 R 120 222
Joe Sakic 19 CAN 9/30/77 L 123 210These are all in early development, we seem to have the idea down but keep getting the odd FileNotFound exception when making an object of the ImportHockeyPlayers class with the parameter of the DAT file.
We might even be on the wrong track with an easier way to do this. To give you an idea of what we want to do...read from the file and be able to pretty much plug in al lthe players into a GUI with a list of the all the players.
Thanks for your time.Thanks for the tip on the date format...good to
know.
public static void main(String[] args)
GUI gui = new GUI();
ImportHockeyPlayers ihp = new
ImportHockeyPlayers("HockeyPlayers.dat");
}It's just being called in the main.
Throws this error:
GUI.java:39: unreported exception
java.io.FileNotFoundException; must be caught or
declared to be thrown
ImportHockeyPlayers ihp = new
ImportHockeyPlayers("HockeyPlayers.dat");
^This error is simply telling you that an exception may occur so you must enclose it in a try catch block or change the main method to throw the exception as follows
public static void main(String[] args) throws
java.io.FileNotFoundException {
GUI gui = new GUI();
ImportHockeyPlayers ihp = new
ImportHockeyPlayers("HockeyPlayers.dat");
}or
public static void main(String[] args) {
GUI gui = new GUI();
try {
ImportHockeyPlayers ihp = new
ImportHockeyPlayers("HockeyPlayers.dat");
catch (FileNotFoundException e) {
System.out.println("error, file not found");
}I would reccomend the second approch, it will be more helpful in debugging, also make sure that the capitalization of "HockeyPlayers.dat" is correct
hope that helps -
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 ! -
How to get the returned error messages in the Try/Catch block in DS 3.0?
A customer sent me the following questions when he tried to implement custom error handling in DS 3.0. I could only find the function "smtp_to" can return the last few lines of trace or error log file but this is not what he wants. Does anyone know the answers? Thanks!
I am trying to implement the Try/Catch for error handling, but I have
hard time to get the return the msg from DI, so I can write it to out
custom log table.
Can you tell me or point me to sample code that can do this, also, can
you tell me which tables capture these info if I want to query it from
DI system tablesHi Larry,
In Data Services XI 3.1 (GAd yesterday) we made several enhancements for our Try/Catch blocks. One of them is the additional of functions to get details on the error that was catched :
- error_message() Returns the error message of the caught exception
- error_number() Returns the error number of the caught exception
- error_timestamp() Returns the timestamp of the caught exception.
- error_context() Returns the context of the caught exception. For example, "|Session Datapreview_job|Dataflow debug_DataFlow|Transform Debug"
In previous versions, the only thing you could do was in the mail_to function specify the number of lines you want to include from the error_log, which would send the error_log details in the body of the mail.
Thanks,
Ben. -
Return in finally block hides exception in catch block
Hi,
if the line marked with "!!!" is commented out, the re-thrown exception is not seen by the caller (because of the return in the finally block). If the line is commented in, it works as I would expect. Is this is bug or a feature? I assume the return removes the call to troubleMaker() from the call stack - including the associated exception...
Christian Treber
[email protected]
public class ExceptionDemo extends TestCase
public void testException()
String lResult = "[not set]";
try
lResult = troubleMaker();
System.out.println("No exception from troubleMaker()");
} catch(Exception e)
System.out.println("Caught an exception from troubleMaker(): " + e);
System.out.println("Result: " + lResult);
public String troubleMaker()
boolean lErrorP = false;
try
if(6 > 5)
throw new RuntimeException("Initial exception");
return "normal";
} catch (RuntimeException e)
System.out.println("Caught runtime exception " + e);
lErrorP = true;
throw new RuntimeException("Exception within catch");
} finally
System.out.println("Finally! Error: " + lErrorP);
if(!lErrorP)
return "finally";This is specified in the Java Language Specification, section 14.19.2 .
-- quote
If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
* If the run-time type of V is assignable to the parameter of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. Then there is a choice:
o If the catch block completes normally, then the finally block is executed. Then there is a choice:
+ If the finally block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
-- end quote
"completing abruptly" (in this instance) means a throw or a return, as specified in section 14.1
Ok? It's not a bug, it's the defined behaviour of the language. And when you think about it, this behaviour gives you the option to do what you want in your finally block.
Maybe you are looking for
-
Standard SAP functionality to send e-mail Text on PO Output?
Hi, I have a new requirement to send E-mail body along with the PO as an attachment to our vendors. We are using '5' as tranmission medium to send the PO as e-mail and we call the Smart Form Interface with the Sender and Receipient information. Is th
-
Hello! I need to delete data of a particular InfoCube. I was wondering if there is a standard function module in SAP which I can modify? Kind regards
-
Printout GR Slip when GR posted via BAPI_GOODSMVT_CREATE
Dear all , We need to printout the slip when we do the Goods receipt with movement type 101 via BAPI_GOODSMVT_CREATE. We set the user parameter NDR with value X in the User parameters to bring the field always on in the MM transactions but when we po
-
Hi Experts, Does any one had success in installing the primavera p6 analytics r8.2 version on obiee 11g? Do we need to install on the server where OBIEE is installed or on a separate server?? Any docs or links would be helpful. appreciate your inputs
-
Hi We have a requirement to extract/write the data from/to Foxpro System using XI. Can anyone suggest how to approach this? JDBC Drivers for Foxpro? XI Supported with Foxpro? Thanks in advance. Regards Chandu