Mailing attachments; java.io.IOException; must be caught or declared to be
I seem to be having trouble setting up to attach a file and I'm getting the error message
java.io.IOException; must be caught or declared to be
//other related code
String bookingFilename = "what ever filename";
// create some properties and get the default Session
Properties props = new Properties();
props.put("mail.smtp.host", host);
Session session = Session.getInstance(props, null);
//session.setDebug(debug);
try {
// create a message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(msgText1);
// create and fill the second message part
MimeBodyPart mbp2 = new MimeBodyPart();
//PROBLEM LINE
mbp2.setFilename(bookingFilename);
// create the Multipart and its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
// add the Multipart to the message
msg.setContent(mp);
// send the message
Transport.send(msg);
} catch (MessagingException mex) {
mex.printStackTrace();
Exception ex = null;
if ((ex = mex.getNextException()) != null) {
ex.printStackTrace();the following is the problem code
mbp2.setFilename(bookingFilename);am I putting the filename in the wrong format?
I'm hoping to specify the exact filename using "if" statements so the current
String bookingFilename = "what ever filename";is just a placeholder
I'd be very grateful for any assitance
eventually I intend to email out 3 seperate attachments at the same time,
from a bank of about 10 files which are either pdf's or word doc's
Dioxin
Lets not go into my lack of Java training just yet :-P
} catch (IOException ioex) {
ioex.printStackTrace();was the block I was missing
I'd also miswritten the problem code...cos I'd been fiddling with other commands
mbp2.attachFile(bookingFilename);well it appears to compile... now to fire off a test email!
cheers
Dioxin
Similar Messages
-
Unreported exception java.lang.Exception; must be caught or declared
I've got a piece of code that's causing an error during compilation.
W:\Java\Covenant\src\covenant\Login.java:174: unreported exception java.lang.Exception; must be caught or declared to be thrownThe line of code it is refering to is:
new Overview().setVisible(true);And it is part of a try/catch statement:
private void logincheck(java.awt.event.ActionEvent evt) {
try {
char[] PasswordInput = Password.getPassword();
String PasswordRaw = new String(PasswordInput);
String Passwordmd5 = md5(PasswordRaw);
String UsernameInput = Username.getText();
URL theUrl = new URL("http://www.phoenixrising.at/iris/validate.php?login=1&u=" + UsernameInput + "&p=" + Passwordmd5 +"");
BufferedReader in = new BufferedReader(
new InputStreamReader(
theUrl.openStream()));
String inputLine = in.readLine();
if (inputLine.equals("valid")) {
new Overview().setVisible(true);
this.setVisible(false);
System.out.println( "You have entered the correct password" );
} else {
System.out.println(theUrl);
in.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} Can anyone see what might be causing this error?Can anyone see what might be causing this error? That line of code declares that it throws exception java.lang.Exception, so you must either catch it ("must be caught" - like you do the more specific Exceptions) or declare your logincheck method to throw it ("or declared to be thrown").
-
in a servlet, I have a class like:
class mydb
public static Connection conn;
public static void init() throws SQLException
// Load the Oracle JDBC driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
conn = DriverManager.getConnection ("jdbc:oracle:oci8:@baby", "scott", "tiger");
public static String getValue() throws SQLException
String curValue="";
// Create a Statement
Statement stmt = conn.createStatement ();
// Select the ENAME column from the EMP table
ResultSet rset = stmt.executeQuery ("select ENAME from EMP");
// Iterate through the result and print the employee names
if (rset.next ())
curValue = rset.getString (1);
// Close the RseultSet
rset.close();
// Close the Statement
stmt.close();
return(curValue);
public static void destroy() throws SQLException
// Close the connection
conn.close();
but when it is called, errors "java.sql.SQLException; must be caught or declared to be thrown." encountered, how to solve this problem? please help.This is part of the Java language.
If a method throws an exception, then
it is telling you that the exception is
something that you should be aware of.
If you call a method which throws this exception, then the method must either catch this exception, or you may decide that this exception should be caught by the calling method.
So, your choices are:
1. Wrap the method call in a try{...} catch block
-or-
2. Change the (calling) method's signature to reflect the fact that this method can cause this exception to be thrown (add a 'throws SQLException' ) at end of signature.
-John
null -
Unreported exception java.rmi.RemoteException; must be caught or declared t
I am receiving an:
unreported exception java.rmi.RemoteException; must be caught or declared to be thrown
error when I attempt to compile the Client.java file.
The Client.java file implements the ATMListener.java interface.
As you will see below, I've stripped them down by taking out all of the code, yet I still receive this error.
Any ideas...
ATMListener.java
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
* @author Eddie Brodie
* @version %I%, %G%
public interface ATMListener extends java.rmi.Remote
Client.java
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.UnknownHostException;
public class Client extends java.rmi.server.UnicastRemoteObject implements ATMListenerWell first off unless I am missing something in the API java.rmi.Remote is an interface not a class so implements not inherits, but I do not really know these classes so I cannot be sure I am not missing something.
As for the unreported exception. What could be causing something like this would be an exception thrown by the constructor of the parent class. Even if you have no constructor written for your class it still has a default constructor which will by default call the super constrcutpor meaning an exception could be thrown from the super constrcutor down to your default constructor where you would not know what to do with it. -
Unreported exception; java.sql.SQLException; must be caught or declared to
Hi everyone,
For my Java course assignment we need to make a small application that uses a MS Access database. But de code below gives me a "Unreported exception; java.sql.SQLException; must be caught or declared to be thrown at line xx" error.
public class ConnectieBeheer
private static Connection con;
private static Statement stmt;
private static ResultSet res;
private static ResultSetMetaData md;
private ConnectieBeheer(){}
public static void openDB() {
Driver driver = new JdbcOdbcDriver();
Properties info = new Properties();
String url = "jdbc:odbc:theater";
con = driver.connect(url, info); <--- Error here
if (con != null)
stmt = con.createStatement(); <--- Error here
DatabaseMetaData dma = con.getMetaData(); <--- Error here
}So I tried this :
public static void openDB() throws SQLException {Now I do not get an error.
The OpenDB method is called from a different class like this :
public static void test1(){
ConnectieBeheer.openDB();
System.out.println("DB opened");
}But now it gives the same "Unreported exception; java.sql.SQLException; must be caught or declared to be thrown at line xx" error but now at the line ConnectieBeheer.openDB();
Why is this? And what can I do to correct this?
Thanks!
Steven.you should read the sun tutoriel about exceptions handling ;
there are two ways to handle an exception : either you redirects it (using "throws" statement, what you did for the openDB method), or you catch it using a try { ... } catch (Exception exc) {}
if you want to get rid of the error what you can do is :
public static void test1(){
try {
ConnectieBeheer.openDB();
} catch (java.sql.SQLException sqle) {
sqle.printStackTrace();
System.out.println("DB opened");
} -
Unreported exception java.sql.SQLException; must be caught or declared to b
I dont know much about java Please help.
I have created following class
import java.sql.*;
public class Updatedb{
private String cofeename ;
private int supid;
public void getfields(String COFNAM , int SUP_ID){
cofeename = COFNAM;
supid = SUP_ID;
public void indb()
throws SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DriverManager.getConnection("jdbc:odbc:myDataSource");
pstmt = con.prepareStatement(
"UPDATE COFFEES SET SUP_ID = " + supid + "WHERE COF_NAME =" + cofeename );
//pstmt.setInt(1, SUP_ID);
//pstmt.setInt(2, COFNAM);
pstmt.executeUpdate();
finally {
if (pstmt != null) pstmt.close();
Now I am calling above class when button is clicked
private void UPDATEActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UPDATEActionPerformed
// TODO add your handling code here:
String input = INPUTFIELD.getText();
Updatedb updateclass = new Updatedb();
updateclass.getfields(input , 20);
updateclass.indb( );
INPUTFIELD.setText( "" );
I am getting above error. Please help me to solve it.
Thanks in advanceA word of honest advice: If you don't understand much of Java, and specifically, if you don't understand how checked exceptions work, you're in over your head looking at JDBC. Step away from it for now, and learn the basics a bit better. Seriously, if you soldier on this way, you'll never really understand what you're doing
-
My function must be caught or declared to be thrown?
hi again.
so here's what's going on.
i'm writing a class that contains a function that will be used as a part of a program. only one parameter will be passed, in this case, BAC.
to test my program, i'm trying to write a simple main function to call the class. here's what it looks like:
public static void main(String[] args) {
String BAC = "teststring";
findbac bac = new findbac();
bac.findbac(BAC);
the function i'm trying to call is findbac(String BAC) in class findbac.
when i compile, i get the error message
29: unreported exception java.io.IOException; must be caught or declared to be thrown
bac.findbac(BAC);
i just started java a few days ago so im not 100% familiar with the throw and catch terms.
what should i do to make this work? thanks.thanks a bunch for the help. still a little confusing, but im gonna sit down and figure it all out tonight after i get home.
and i tried putting in the code Valavet suggested, and it compiles now! but when i run it, i get a new error:
java.lang.ArrayIndexOutOfBoundsException: 2
at findit.findbac.findbac(findbac.java:108)
at findit.findbackclass.main(findbackclass.java:37)
Exception in thread "main"
Java Result: 1
the two lines of code are
experiments[experimentnumber-1] = dataline.substring(beginningIndex, endIndex);
and
bac.findbac(BAC);
respectively.
what do they mean by array index out of bounds? i know my array index is correct.
do { //this do-while loop writes each experiment's result (as a string) to the experiments[] matrix.
foundIndex = dataline.indexOf(comma, fromIndex);
if (foundIndex >= 0) {
experimentnumber++;
fromIndex = foundIndex + 1;
endIndex = fromIndex;
if (experimentnumber >= 1){
experiments[experimentnumber-1] = dataline.substring(beginningIndex, endIndex);
beginningIndex = fromIndex;
} while (foundIndex >= 0); -
Must be caught or declared to be thrown...
how would i go about something like that?
import java.util.*;
public class GameLauncher{
public static void main( String [] args) {
SellGame game = new SellGame();
game.startGame();
____________________________________________________________________how would i go about something like that?I am guessing that your program will not compile... something like this:
% cat HelloWorld.java
public class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello, world!");
java.lang.Thread.sleep(500);
% javac -g HelloWorld.java
HelloWorld.java:5: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
java.lang.Thread.sleep(500);
^
1 errorRefer to this section of the Tutorial for an explanation:
Exception Handling Statements
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/exception.html
Hope this helps.
"Troubleshooting Guide for J2SE 5.0",
http://java.sun.com/j2se/1.5/pdf/jdk50_ts_guide.pdf -
Conn.rollback() must be caught or declared to be thrown
Hi, I'm having problems compiling the following code
private void toInsert(String insert_foo, int insert_bar) {
InitialContext context = null;
Connection conn = null;
PreparedStatement pstmt= null;
try {
context = new InitialContext();
DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/TestDB");
conn = ds.getConnection();
conn.setAutoCommit(false);
pstmt = conn.prepareStatement("INSERT into testdata values(?, ?)");
pstmt.setString(1, insert_foo);
pstmt.setInt(2, insert_bar);
pstmt.executeUpdate();
conn.commit();
conn.setAutoCommit(true);
pstmt.close();
pstmt = null;
conn.close();
conn = null;
context.close();
context = null;
catch (Exception e) {
conn.rollback();
finally {
if (pstmt != null) {
try { pstmt.close(); }
catch (SQLException e) {;}
pstmt = null;
if (conn != null) {
try { conn.close(); }
catch (SQLException e) {;}
conn = null;
if (context != null) {
try { context.close(); }
catch (NamingException e) {;}
context = null;
}I got this error when I try to compile the above;
unreported exception java.sql.SQLException; must be caught or declared to be thrown
conn.rollback();
I search and read through a lot of posts here that rollback() could be used in the catch block but why I can't I compile it?
Please help me out, thank you.
puzzled....Is it similiar to factory methods? No.
I've read up on this:
http://www.javaworld.com/javaworld/javaqa/2001-05/02-qa-0511-factory.html?
"small boy with a pattern" syndrome strikes again.
Could you assist to help me in giving me guidelines
for writing the database utilites class?
Appreciated...
public final class DatabaseUtils
public static void close(Connection c)
if (c != null)
try
c.close();
catch (SQLException e)
// print stack trace or, better yet, log the exception with Log4J
// same for other close operations on ResultSet and Statement
public void rollback(Connection c)
if (c != null)
try
c.rollback();
catch (SQLException e)
// print stack trace or, better yet, log the exception with Log4J
}% -
Must be caught or declared to be thrown ! Help !
Dear Java People,
I have only one error in my program in the TryVectorAndSort class
"Unreported exception (InvalidUserInputException)
Must be caught or declared to be thrown lines 41,49"
>> String firstName = in.readString().trim();
>> String lastName = in.readString().trim();
so the error in the above 2 lines points to the readString() method
which is below
public String readString() throws InvalidUserInputException
if(readToken() == tokenizer.TT_WORD || ttype == '\"' || ttype == '\'')
return tokenizer.sval;
else
throw new InvalidUserInputException(" readString() failed. " + " Input data is not a string");
below is the entire FormattedInput class
Thank you in advance
Norman
import java.io.*;
import java.util.*;
public class FormattedInput
// Method to read an int value
public int readInt()
for(int i = 0; i < 2; i++)
if(readToken() == tokenizer.TT_NUMBER)
return (int)tokenizer.nval; // value is numeric so return as int
else
System.out.println("Incorrect input: " + tokenizer.sval +
" Re-enter as integer");
continue; //retry the read operation
} //end of if statement
System.out.println("Five failures reading an int value" + " - program terminated");
System.exit(1); // end the program
return 0;
} //end of method
public double readDouble() throws InvalidUserInputException
if(readToken() != tokenizer.TT_NUMBER)
throw new InvalidUserInputException(" readDouble() failed. " + " Input data not numeric");
return tokenizer.nval;
public String readString() throws InvalidUserInputException
if(readToken() == tokenizer.TT_WORD || ttype == '\"' || ttype == '\'')
return tokenizer.sval;
else
throw new InvalidUserException(" readString() failed. " + " Input data is not a string");
//helper method to read the next token
private int readToken()
try
ttype = tokenizer.nextToken();
return ttype;
catch(IOException e)
e.printStackTrace(System.err);
System.exit(1);
return 0;
//object to tokenize input from the standard input stream
private StreamTokenizer tokenizer = new StreamTokenizer(
new BufferedReader(
new InputStreamReader(System.in)));
private int ttype; //stores the token type code
import java.io.*;
import java.util.*;
public class TryVectorAndSort
public static void main(String[] args)
Person aPerson; // a Person object
Crowd filmCast = new Crowd();
//populate the crowd
for( ; ;)
aPerson = readPerson();
if(aPerson == null)
break; // if null is obtained we break out of the for loop
filmCast.add(aPerson);
int count = filmCast.size();
System.out.println("You added " + count + (count == 1 ? " person": " people ") + "to the cast.\n");
//Show who is in the cast using an iterator
Iterator myIter = filmCast.iterator();
//output all elements
while(myIter.hasNext() )
System.out.println(myIter.next());
}//end of main
//read a person from the keyboard
static public Person readPerson()
FormattedInput in = new FormattedInput();
//read in the first name and remove blanks front and back
System.out.println("\nEnter first name or ! to end:");
String firstName = in.readString().trim(); //read and trim a string
//check for a ! entered. If so we are done
if(firstName.charAt(0) == '!')
return null;
//read the last name also trimming the blanks
System.out.println("Enter last name:");
String lastName = in.readString().trim(); // read and trim a string
return new Person(firstName, lastName);
//when I ran the program the output I received was:
import java.io.StreamTokenizer;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class InvalidUserInputException extends Exception
public InvalidUserInputException() { }
public InvalidUserInputException(String message)
super(message);
public class Person implements Comparable
public Person(String firstName, String lastName)
this.firstName = firstName;
this.lastName = lastName;
public String toString()
return firstName + " " + lastName;
//Compare Person objects
public int compareTo(Object person)
int result = lastName.compareTo(((Person)person).lastName);
return result == 0 ? firstName.compareTo(((Person)person).firstName):result;
private String firstName;
private String lastName;
import java.util.*;
class Crowd
public Crowd()
//Create default Vector object to hold people
people = new Vector();
public Crowd(int numPersons)
//create Vector object to hold people with given capacity
people = new Vector(numPersons);
//add a person to the crowd
public boolean add(Person someone)
return people.add(someone);
//get the person at the given index
Person get(int index)
return (Person)people.get(index);
//get the numbers of persons in the crowd
public int size()
return people.size();
//get people store capacity
public int capacity()
return people.capacity();
//get a listIterator for the crowd
public Iterator iterator()
return people.iterator();
//A Vector implements the List interface (that has the static sort() method
public void sort()
Collections.sort(people);
//Person store - only accessible through methods of this class
private Vector people;
}Dear Levi H,
When I changed the catch block type to
String lastName= "";
try
lastName = in.readString().trim(); //read and trim a string
catch(InvalidUserInputException e)
e.printStackTrace(System.err);
I no longer have errors in the driver class but in the FormattedInput
class there are new errors that say:
"FormattedInput.java": Error #: 204 : illegal start of expression at line 49,68
"FormattedInput.java": Error #: 206 : malformed expression at line 39,49
Help !
Norman -
Exception must be caught or declared to be thrown?
got two errors when compling:
TryCalendar.java [20:1] unreported exception InvalidUserInputException; must be caught or declared to be thrown
int day = in.readInt();
^
TryCalendar.java [21:1] unreported exception InvalidUserInputException; must be caught or declared to be thrown
int month = in.readInt();
Is there anyone could kindly tell me how to solve? Thank you very much! The short source code as following:
import java.util.GregorianCalendar;
import java.text.DateFormatSymbols;
public class TryCalendar {
public static void main(String[] args) {
FormattedInput in = new FormattedInput();
// Get the date of birth from the keyboard
System.out.println("Enter your birth date as dd mm yyyy: ");
int day = in.readInt();
int month = in.readInt();
int year = in.readInt();
// Create birht date calendar - month is 0 to 11
GregorianCalendar birthdate = new GregorianCalendar(year, month-1, day);
GregorianCalendar today = new GregorianCalendar(); // Today's date
// Create this year's birthday
GregorianCalendar birthday = new GregorianCalendar(
today.get(today.YEAR),
birthdate.get(birthdate.MONTH),
birthdate.get(birthdate.DATE));
int age = today.get(today.YEAR) - birthdate.get(birthdate.YEAR);
String[] weekdays = new DateFormatSymbols().getWeekdays(); // Get day names
System.out.println("You were born on a " + weekdays[birthdate.get(birthdate.DAY_OF_WEEK)]);
System.out.println("This year you " + (birthday.after(today) ?"will be " : "are " ) + age + " years old.");
System.out.println("This year your birthday " + (today.before(birthday)? "will be": "was") + "on a " + weekdays[birthday.get(birthday.DAY_OF_WEEK)]);
}The compiler error has to do with "Exceptions"
"Exceptions" are things that might go wrong while the program is running. In this case, the user might type "ABC" when the program is trying to read a number using readInt. If the user does this, then that line of code will "throw" an "InvalidUserInputException".
Your code must "handle" the exception. There are two ways to do this.
Note that your code is part of a method, namely, the main method
public static void main(String args[])
int day = in.readInt(); // Exception might be thrown here
} // end of main methodThe first way to deal with the Exception is to decide that main will throw it. Already, readInt throws the Exception to main, now we will make main in turn throw the exception back to whatever called it.
This can be done as follows. Note the change to the declaration of main.
public static void main(String args[]) throws InvalidUserInputException
int day = in.readInt(); // Exception might be thrown here
} // end of main methodThen your code should compile and run. This method is not recommended - if the user types in ABC, the program will crash with a cryptic error message.
It is much better, if readInt throws the Exception, to have your code catch it. To do this, the code that might throw the exception must be contained in a try block, which must be followed by a catch block.
public static void main(String args[])
try {
int day = in.readInt(); // Exception might be thrown here
} // end of try block
catch (InvalidUserInputException iue) {
... // code to handle the exception
} // end of main methodWhat this means is that java will "try" to perform the code in the try block, and if the user types ABC instead of a number, the InvalidUserInputException thrown by int day=in.readInt() will be "caught", and the code in the catch block will run. The code in the catch block can be anything you like. The most sensible thing to do would be to print some error message informing the user that they typed something wrong. Maybe something like:
boolean done = false;
int day,month,year;
do {
try {
System.out.println("Enter your birth date as dd mm yyyy: ");
day = in.readInt(); // line (1)
month = in.readInt(); // line (2)
year = in.readInt(); // line (3)
done = true; // line (4)
catch (InvalidUserInputException iuie) {
System.out.println("Are you trying to confuse me? I'm only a poor harmless computer! "); // line (5)
System.out.println("dd mm and yyyy must be numbers!");
} while (!done);If an Exception is thrown on lines (1), (2) or (3), then line (4) will not be reached - instead, the program will run from line (5). Since done is still false, the program will loop back to ask for the birthdate again.
If no exception is thrown, line (4) ensures that the loop will finish, and the catch block is skipped altogether.
Hope that makes things clearer :-)
Yours, Mike H... -
Java.io.IOExecption; must be caugh or declared to be thrown - omg?
Hello everybody,
I'm kind of new to java and as part of a school project I've got to make a fully functional program.
When compiling (I use BlueJ, if it matters), I'm getting this message:
java.io.IOExecption; must be caugh or declared to be thrown
What does this mean?
I'm missing something(obviously), the IOExection, I think I saw that a mate from class has some part of code which does something when the wrong datatype or input is inputed, te IOExecption thingy.
Please help, I need to do this very quickly, and time is running out!IOException is a "checked exception". That means that it's an exception that you must handle.
Exceptions are classes that represent something going wrong in the program. They're not likely to go wrong (that's why they're called "exceptions" and not "typicals"), but the developer of the API you're using felt that it was likely enough, and that it was something that you could reasonably deal with if it does go wrong. The exception represents that unlikely event.
Your job is to write some code that handles the exception. One way to handle it is just to declare your method as throwing that exception, and let the caller handle it. Another way to handle it is just to tell the user that it happened. In other cases, you can do more subtle handling -- say, you might be able to fix the core problem that the exception represents.
Read about try/catch blocks in the tutorials. -
How to slove follwoing error "Unreported exception java.io.IOException;"
Currently I'm using following:
XP Professional
J2sdk1.4.2_01
Xerces-2_5_0
Xalan-j_2_5_1
Jakarta-tomcat-4.1.27
Jdom-b9
Current Classpath setting
User variables
PATH = c:\bmrt2.5\bin; c:\j2sdk\bin;%PATH%;%JAVA_HOME%\bin;
CLASSPATH=.;c:\xerces\xmlParserAPIs.jar;c:\xerces\xercesImpl.jar;
c:\xerces\xercesSamples.jar;c:\xalan\xercesImpl.jar;c:\xalan\xmlapis.jar;c:\xalan\xalan.jar;c:\tomcat\lib\webserver.jar;c:\tomcat\lib\jasper.jar;c:\tomcat\lib\xml.jar;c:\tomcat\common\lib\serlet.jar;c:\tomcat\lib\tools.jar; c:\tomcat\lib\tools.jar;c:\jdom\build\jdom.jar;
CATALINA_HOME= c:\tomcat
JAVA_HOME= c:\j2sdk
System variables
PATH=%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;
c:\j2sdk\bin;%Path%;%JAVA_HOME%\bin;
CLASSPATH=.;c:\xerces\xmlParserAPIs.jar;c:\xerces\xercesImpl.jar;
c:\xerces\xercesSamples.jar;c:\xalan\xercesImpl.jar;c:\xalan\xmlapis.jar;c:\xalan\xalan.jar;c:\tomcat\lib\webserver.jar;c:\tomcat\lib\jasper.jar;c:\tomcat\lib\xml.jar;c:\tomcat\common\lib\serlet.jar;c:\tomcat\lib\tools.jar; c:\tomcat\lib\tools.jar;
CATALINA_HOME= c:\tomcat
JAVA_HOME= c:\j2sdk
Program
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.jdom.*;
import org.jdom.Element;
import org.jdom.Document;
import org.jdom.output.XMLOutputter;
import org.jdom.input.SAXBuilder;
import org.jdom.Attribute;
import java.util.List;
public class AddToList extends HttpServlet
public Document getDocument(File sourceFile, PrintWriter errorsOut)
try
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(sourceFile);
return document;
catch(JDOMException e)
errorsOut.print("there was a problem building the document: " e. getMessage()"<br/>"+ "Returning blank document.");
return new Document(new Element("blank"));
public void saveDocument(Document saveDoc, File saveFile, PrintWriter errorsOut)
try
FileOutputStream outStream= new FileOutputStream(saveFile);
XMLOutputter outToFile= new XMLOutputter(" ",true);
outToFile.output(saveDoc, outStream);
outStream.flush();
outStream.close();
catch (IOException e)
errorsOut.print("Can't save order.xml: " + e.getMessage()+"<br />");
public void addItem(Element orderElement, String product_id, String quant)
Element newItem =new Element("item");
newItem.setAttribute("product_id", product_id);
Element quantity =new Element("quantity");
quantity.addContent(quant);
newItem.addContent(quantity);
orderElement.addContent(newItem);
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
String thisProduct_id=request.getParameter("addProduct_id");
String thisQuantity=request.getParameter("addQuantity");
response.setContentType("text/html");
PrintWriter out= response.getWriter();
out.print("Adding "+ thisQuantity + "of item to chart "+ thisProduct_id +" ... ");
File orderFile = new File ("file:///c:/jdk1.3/orders.xml");
if(!orderFile.exists())
out.print("Creating ordersrocks....<br />");
Element root= new Element("orders");
root.addContent(" ");
Document document = new Document(root);
saveDocument (document, orderFile, out);
else
out.print("Orders File Exists.");
Document document =getDocument(orderFile, out);
HttpSession session =request.getSession(true);
String session_id= session.getId();
Element root =document.getRootElement();
List orders =root.getChildren();
int num_orders =orders.size();
boolean orderExists =false;
int orderIndex =0;
for(int i=0; i<num_orders; i++)
Element iOrder=(Element)orders.get(i);
String iOrder_id=iOrder.getAttributeValue("order_id");
if (iOrder_id.equals(session_id))
orderExists=true;
orderIndex=i;
break;
if(!orderExists)
Element order =new Element("order");
order.setAttribute("order_id", session_id);
Element status =new Element("order_status");
status.setText("open");
order.addContent(status);
addItem(order, thisProduct_id, thisQuantity);
root.addContent(order);
else
Element thisOrder=(Element)orders.get(orderIndex);
boolean itemExists=false;
int itemIndex =0;
List items =thisOrder.getChildren("item");
int num_items =items.size();
for(int i=0; i<num_items; i++)
Element iItem=(Element)items.get(i);
String iProduct_id =iItem.getAttribute("product_id").getValue();
if(iProduct_id.equals(thisProduct_id))
itemExists =true;
itemIndex =i;
break;
if(itemExists)
Element thisItem=(Element)items.get(itemIndex);
String currentQuantity= thisItem.getChildText("quantity");
int newQuantity = Integer.parseInt(currentQuantity)+ Integer.parseInt(thisQuantity);
String strQuantity= new String().valueOf(newQuantity)+1;
thisItem.getChild("quantity").setText(strQuantity);
else
addItem(thisOrder, thisProduct_id, thisQuantity);
saveDocument (document, orderFile, out);
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
doGet(request, response);
When I compile above program, it gives me following error.
Error
C:\tomcat\webapps\book\WEB-INF\classes>javac AddToList.java
AddToList.java:19: unreported exception java.io.IOException; must be caught
or declared to be thrown
Document document = builder.build(sourceFile);
^
1 error
Any help regarding this will be appreciated
Thank you
RocksObadare
Thank for your help, my program compile successfully. But now I�m facing different kind of error on Tomcat; why it gives me following error and how do I solve it
http://localhost:8080/rock/servlet/AddToList
Following Error generate by Tomcat:
Http Status 500-
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Cannot allocate servlet instance for path /rock/servlet/AddToList
at org.apache.catalina.servlets.InvokerServlet.serveRequest(InvokerServlet.java:435)
at org.apache.catalina.servlets.InvokerServlet.doGet(InvokerServlet.java:180)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:247)
root cause
java.lang.NoClassDefFoundError: org/jdom/JDOMException
at java.lang.Class.newInstance0(Native Method)
at java.lang.Class.newInstance(Class.java:237)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:903)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:668)
at org.apache.catalina.servlets.InvokerServlet.serveRequest(InvokerServlet.java:416)
at org.apache.catalina.servlets.InvokerServlet.doGet(InvokerServlet.java:180)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:247)
The following is my configuration
Classpath= .;c:\xalan\bin\xalan.jar;c:\xalan\bin\xml-apis.jar;c:\xerces\xmlParserAPIs.jar;c:\xerces\xercesImpl.jar;c:\tomcat\common\lib\servlet.jar;c:\jdom\build\jdom.jar;
Java_Home=c:\jdk1.3
Catalina_Home=c:\tomcat
Server.xml
<Engine name="Standalone" defaultHost="localhost" debug="0">
<Host name="localhost" debug="0" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<Context path="/rock" docBase="rock" debug="0"
reloadable="true" crossContext="true">
P.S When I try to build javadoc it give me following error:
C:\jdom>build javadoc
JDOM Build System
Building with classpath c:\jdk1.3\lib\tools.jar;.\lib\ant.jar;.\lib\xml-apis.jar
;.\lib\xerces.jar;
Starting Ant...
Buildfile: build.xml
[javadoc] Constructing Javadoc information...
[javadoc] Building tree for all the packages and classes...
[javadoc] Building index for all the packages and classes...
[javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
transform.TransformerFactory#getFeature
[javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
transform.TransformerFactory#getFeature
[javadoc] Building index for all classes...
[javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
transform.TransformerFactory#getFeature
[javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
transform.TransformerFactory#getFeature
[javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
transform.Transformer
[javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
transform.Transformer
[javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
transform.Transformer JAXP TrAX Transformer
[javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
transform.TransformerFactory#getFeature
[javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
transform.TransformerFactory#getFeature
[javadoc] javadoc: warning - Tag @link: Class or Package not found: java.lang.
Double#NaN
[javadoc] Generating C:\jdom\build\apidocs\stylesheet.css...
[javadoc] 10 warnings
BUILD SUCCESSFUL
Total time: 12 seconds -
Handling java.io.IOException ?
Hi !
Keep getting the following error :
"Unreported Exception java.io.IOException; must be caught or declared to be thrown"
Using a throw as in "public void doGet(HttpServletResuest svreq, HttpServletResponse svresp) throws IOException" works well but
I want to catch it along with SQLException and Exception :
... (fragment code follows) ...
public class LstEmpHandle extends HttpServlet
public void doGet(HttpServletRequest svreq, HttpServletResponse svresp)
{ ... some declarations ...
try { ... more code...
} catch (IOException exc ) {"IOException: "+ exc.getErrorCode() + " : " + exc.getMessage();}
catch (SQLException exc) {..;.;}
catch (Exception exc){...}
finally (...)
That is the only complain the compiler has got !Hi !
I do have "System.out.println" which I did not include in my fragment code.
If I do this, there are no compile-time errors
public void doGet(HttpServletRequest svreq, HttpServletResponse svresp) throws IOException
{ ResultSet rs = null;
Connection myconn = null;
Statement mystmt = null;
int rowCnt = 0;
PrintWriter out =svresp.getWriter() ;
svresp.ContentType("text/html");
try { ... code code code ...
} catch ( SQLException exc)
{ System.out.println("error code : " + exc.getErrorCode() + " :: " + exc.getErrorMessage());}
catch (Exception exc)
{System.out.println("Exception :" + exc.getErrorMessage());}
finally { try ... etc ...}
However, if I want to trap the IOException along with other exceptions I get the aforementioned error:
public void doGet(HttpServletRequest svreq, HttpServletResponse svresp)
{ ResultSet rs = null;
Connection myconn = null;
Statement mystmt = null;
int rowCnt = 0;
PrintWriter out =svresp.getWriter() ; //javac throws compile time error here
svresp.ContentType("text/html");
try { ... code code code ...
} catch (IOException exc)
{ System.out.println(IOException occurred :" + exc.getMessage());}
catch ( SQLException exc) // here is where error is at compile time
{ System.out.println("error code : " + exc.getErrorCode() + " :: " + exc.getErrorMessage());}
catch (Exception exc)
{System.out.println("Exception :" + exc.getErrorMessage());}
finally { try ... etc ...} -
Trying to read a file, and it gives me "java.io.IOException"
I'm writing a little swing text editor for my first java project, and the open method is like this:
public void openFile() throws IOException {
JFileChooser chooseOpen = new JFileChooser();
chooseOpen.showOpenDialog(null);
File openFile = chooseOpen.getSelectedFile();
FileReader in = new FileReader(openFile);
BufferedReader br = new BufferedReader(in);
String fileText = br.readLine();
output.setText(fileText);
It seems like it should work fine to me, you choose a file, and it opens it, then outputs it to my textArea. I even have it throwing IOException. Why is it giving me that message then? (this is the only method I'm having a problem with.)
the full error message is:
unreported exception java.io.IOException; must be caught og declared to be thrown
openFile();
^
1 error
thanks,
alexopenFile throws an IOException. This is a checked exception which means you must either put it in a try/catch block or throw it in the caller.
Maybe you are looking for
-
Design Editor Crashes on editing USER TEXT
I am running Designer 9i version 9.0.2.10 on windows XP. Everytime I try to use either Text Editor or HTML editor for editing user text under USER TEXT tab of a module definition, the Designer crashes. I have checked the Text Editor options under the
-
Error while setting up J2ee agents
Hi, http://www.oracle.com/webfolder/technetwork/tutorials/obe/fmw/odi/odi_11g/setup_jee_agent/setup_jee_agent.htm I am trying to set up J2EE agents for ODI using above link on lynux, in this process I am getting below error while giving createCred co
-
How to suppress the name if it is blank in sap script
hi I have one doubt iam print NAME2 in sap script. if NAME2 is balnk blank line is coming but my requiremt is if it is balnk, blank line sould not come i tried with NAME2(I) but it is not working please give the solutions at the earliest very urgent
-
My I phone 4s does not have an update option to get IOS7. How do I downloead?
-
Download from iTune store gets disrupted
Hi, I got this problem while downloading. Its like whenever i pause my downloads or my cable internet connection gets disconnected, then the download starts from the beginning again ie from ZERO. I had read somewhere the download should have continue