Question about throwing exceptions

hi,
i am trying to throw a FileNotFoundException in a certain situation, but Eclipse is giving me the 'unhandled FileNotFoundException' error and insisting I wrap the 'throw' statement in a try/catch statement.
Is that right? is it just a bug in eclipse or does this exception insist i catch the very exception i am trying to throw?
thanks!

You can throw it, but you have to declare that your method throws it.
void myMethod() throws FNFExc {
    throw new FNFExc("Me no findey");
}

Similar Messages

  • Question about throws exception in interface and realized class

    Hi,all
    If I define a method In the interface like that-
    public void Execute() throws NumberFormatException; In the realized class, I can define this method like that-
    public void Execute() throws RuntimeException{
            System.out.println("test");       
    }This is a right realization. But if I manage it to throws Exception or to throws Throwable in the class it leads a error. Why add this restrict only to Exception? What is the purpose of this way?
    Greetings and thanks,
    Jason

    When you say "throws NumberFormatException" you are really saying:
    When using classes implementing this interface, you have to be prepared to deal with them throwing a NumberFormatException. Other exceptions won't happen.
    When you come to implement it, it might not be possible for it to throw a NumberFormatException, so there's no reason why you should have to lie about that. Code handling it directly will be fine (it doesn't throw a NFE) and code handling it via the interface will be fine (it will handle NFEs, they just don't happen).
    If your concrete implementation throws other sorts of exception, such as Exception or IOException, and so on, it's incompatible with code that's manipulating the interface. The interface says "NFEs might get thrown, nothing else will." while your implementation says "IOExceptions might get thrown".
    So that explains why you can't use arbitrary exceptions. The special case is RuntimeException. RuntimeExceptions don't have to be caught, and it's expected that they can happen at any time - so there's no point trying to catch and handle them as a general case.
    The classic example of a RuntimeException is a NullPointerException. You don't need to declare your method as throwing a NullPointerException even though it might get thrown. And you don't have to add NullPointerException to the throws part of the interface definition, because you already know that the concrete implementation could throw a NPE at any time.
    Hope that helps (a little).
    I'd recommend reading the API documentation on RuntimeException and Exception to get a clearer insight into this.
    Dave.

  • Quick question about an exception problem

    Hi all,
    I'm doing a homework problem with exceptions and there is an outline I have to fill in with some exception handling. There are 2 parts of the problem I'm not sure about that deal with checked and unchecked exceptions and passing exceptions to a calling method.
    Here's the problem: in the following method, the call to getStudentNumber( ) may throw a BadNumberException or a FileIOException. Modify the code (aka add try/catch blocks etc.) to do the following.
    1. Pass the BadNumberException on to the calling method. It is not a checked exception.
    2. Pass FileIOException on to the calling method. It is a checked exception.
    Here is the code outline:
    public void reportStudents() {
    int number;
    while(true) {
    number = getStudentNumber();
    setStudentNumber(number);
    } }I know I need to declare the 2nd exception but I'm not sure the syntax of doing so. Any help would be appreciated. Thanks.

    See this tutorial for the information:
    http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

  • About throwing exceptions

    First of all, did everyone enjoy the midweek vacation(1 may) :-)
    Here is a question:
    What i'm trying to do is extracting an array of known length (this is bContent) out
    of another array. If the bContent is larger than the former I'll get a NegativeArraySizeException
    when trying new byte[bToExtract.length - bContent.length]. So I catch it.
    I also rethow it because I'll reuse it in the main program to set an errorstatus.
    But the method still has to return something + The whole thing won't compile.
        * The extract method takes his own content from the beginning
        * of a byte array and returns the byte array minus the exracted content.
        * @param bToExtract The putative ByteArray where fielddata has to be
        *                   extracted from.
        * @return The remains of the input ByteArray after extraction
       public byte[] extract(byte[] bToExtract) throws NegativeArraySizeException
          try
          byte[] bToReturn = new byte[bToExtract.length - bContent.length];
          for(int i = 0; i < bContent.length; i++)
                { bContent[i] = bToExtract;}
    for(int i = bContent.length; i < bToExtract.length; i++)
    { bToReturn[i-bContent.length] = bToExtract[i];}
    return bToReturn;
    catch(NegativeArraySizeException e1)
    clear();
    return bToExtract; // or is it first throw then return ?
    throw e1;
    The compiler says:
    c:\xxx\xxx\xxx.java:167: unreachable statement
    throw e1;
    1 error
    If i put throw e1 first and then return:
    throw e1;
    return bToExtract;The compiler says:
    c:\xxx\xxx\xxx.java:167: unreachable statement
    return bToExtract;
    1 error
    What do I need to do ?

    I don't think i can do it without a return, because the method has been
    defined in an abstract class. And changing this would mean i have to review
    the whole concept, and i'm not really eager to do this at this point, if you know what i mean
    So, How could i return something to notify the method calling program? returning a an array
    greater than the former is maybe an option, and check it with an if then else, but then
    i need to allocate more memory

  • Question about throws and superclasses

    Let's say I have something like the following:
    public class Foo
        public Foo( String x ) Throws SomeException
            //code
            if( someProblem )
                throw new SomeException();
    public class Bar extends Foo
        int someVal;
        public Bar( String x, int val )
            super( x );
            someVal = val;
    }Is it correct to add a throws clause to the constructor for Bar?

    Is it correctIt's not just 'correct', it's required. The super() line can throw whatever the Foo() constructor throws.
    Did you try it with and without?

  • A question about ROLLBACK and Unhandled Exceptions in stored subprograms

    Hi,
    Oracle version :   Enterprise Edition Release 11.2.0.1.0 - 64bit
                      OS :   Linux Fedora Core 17 (X86_64)
    At chapter 11 of the online PL/SQL Reference, here is what oracle says about Unhandled Exceptions :
    If a stored subprogram exits with an unhandled exception, PL/SQL does not roll back database changes made by the subprogram.
    I tried the following code:
    code
    HOST clear;
    SET SQLBLANKLINES ON;
    ALTER SESSION SET PLSQL_WARNINGS='ENABLE:ALL';
    DROP TABLE tmptab;
    CREATE TABLE tmptab(n NUMBER);
    CREATE OR REPLACE PACKAGE pkg1_pkg
    AUTHID DEFINER
    AS
        MYEXCEPTION EXCEPTION;
        PRAGMA      EXCEPTION_INIT(MYEXCEPTION, -20001);
    END;
    SHOW ERRORS;
    -- This is a subprogram which exists
    -- with an unhandled exception
    CREATE OR REPLACE PROCEDURE mytestProc
    AUTHID DEFINER
    IS  
    BEGIN
        INSERT INTO tmptab(n) VALUES(100);
        -- So this unhandled exception does a ROLLBACK
        -- which cancels the previous INSERT statement
        RAISE pkg1_pkg.MYEXCEPTION;
    END mytestProc;
    SHOW ERRORS;
    BEGIN
        mytestProc();
    END;
    SELECT * FROM tmptab;
    And here is the output
    BEGIN
    ERROR at line 1:
    ORA-20001:
    ORA-06512: at "TRAINING.MYTESTPROC", line 6
    ORA-06512: at line 2
    no rows selected
    The fact that SELECT * FROM tmptab gives: no rows selected indicates that the unhandled exception in the stored subprogram myTestProc did in fact a ROLLBACK for the INSERT statement into the tmptab table.
    So I don't understand why in the documentation it has been mentioned that no ROLLBACK is not done.
    Could anyone kindly make some clarification on this?
    Thanks in advance,
    Regards,
    Dariyoosh

    Hi,
    If a stored subprogram exits with an unhandled exception, PL/SQL does not roll back database changes made by the subprogram.
    What's going on here is that an anonymous block (which is not stored) exits with an unhandled exception, and that does roll back uncommitted transactions.
    I created a procedure to see how many rows are in tmptab:
    CREATE OR REPLACE PROCEDURE tmptab_cnt (in_txt  IN  VARCHAR2)
    AUTHID DEFINER
    AS
         n    PLS_INTEGER;
    BEGIN
         SELECT  COUNT (*)
         INTO    n
         FROM    tmptab;
        dbms_output.put_line (  n
                             || ' rows in tmptab in '
                             || in_txt
    END  tmptab_cnt;
    and called it from your procedure, and also from your anonymous block:
    CREATE OR REPLACE PROCEDURE mytestProc
    AUTHID DEFINER
    IS  
    BEGIN
        INSERT INTO tmptab(n) VALUES(100);
        tmptab_cnt ('mytestProc');
        RAISE pkg1_pkg.MYEXCEPTION;
    END mytestProc;
    SHOW ERRORS;
    BEGIN
        mytestProc();
    EXCEPTION
      WHEN OTHERS THEN
        tmptab_cnt ('anonymous block');
        RAISE;
    END;
    The output from this is:
    Procedure created.
    No errors.
    1 rows in tmptab in mytestProc
    1 rows in tmptab in anonymous block
    BEGIN
    ERROR at line 1:
    ORA-20001:
    ORA-06512: at line 6
    no rows selected
    As you can see, there was 1 row in the table after the procedure returned to the anonymous block.
    Thanks for posting such a clear and complete test script; that really helps.
    How did you format the code, with the green background and the title?

  • Some questions about how to change scenes

    i have something like the following:
    fxml (view/main/MainMenu.fxml):
    <Scene fx:controller="view.main.CtrlMainMenu" xmlns:fx="http://javafx.com/fxml" stylesheets="view/main/main.css">
        <GridPane xmlns:fx="http://javafx.com/fxml" alignment="center" id="backgorund" hgap="10" vgap="10">
            <!--other panes -->
            <VBox spacing="8" GridPane.columnIndex="0" GridPane.rowIndex="1">
                <Button text="Start" onAction="#Start"/>
                <Button text="Options" onAction="#Options"/>
                <Button text="Exit" onAction="#Exit"/>
            </VBox>
        </GridPane>
    </Scene>main loop (cotroller/main.java):
    public class main extends Application{
        public static void main(String[] args){
            launch(main.class, args);
        public void start(Stage stage) throws Exception{
            stage.setTitle(CtrlLanguage.get(CtrlLanguage.TITLE));
            CtrlMainMenu main = new CtrlMainMenu();
            Scene scene = main.main();          //don't know how to make Scene scene = (Scene)FXMLLoader.load(getClass().getResource("MainMenu.fxml")); work on here since MainMenu.fxml is in view/main while the main class is in controller and ended up putting CtrlMainMenu in the view although is not very correct
            stage.setScene(scene);
            stage.setWidth(1080);
            stage.setHeight(720);
            stage.show();
    }view controller (view/main/CtrlMainMenu.java):
    public class CtrlMainMenu{
        //other buttons actions
        public Scene main() throws Exception{
            return (Scene)FXMLLoader.load(getClass().getResource("MainMenu.fxml"));
        @FXML protected void Start(ActionEvent event){
        @FXML protected void Options(ActionEvent event){
        @FXML protected void Exit(ActionEvent event){
            System.exit(0);          //is there any other way to finish the program than using a system.exit?
    }got few questions currently:
    1. i'd like to be able to keep using CtrlMainMenu for other buttons while the ones that appear there go to the main (since will be reusing those classes from other scenes)
    tried adding fx:controller on panes instead of the scene, but it doesnt work at all (it crashes) else directly in CtrlMainMenu change the scenes of the stage, but then, i have to send the stage to every controller i use? (or how do i know the stage of the scene?)
    and in the case of options, i'd like after done, go back to the previous scene, is that possible? if so, how?
    2.if i want to implement languages, how do i do to change the text? tried with setText() but depending on where do i put it, it crashes, so dont know where do i have to put it
    3.im doing a game that may have different number of players, so, is there some way to erase/hide/add data from a gridpane with fxml?

    1. ok, found the way to change scenes, with this way:
    @FXML protected void Start(ActionEvent event) throws Exception{
         Node node = (Node)event.getSource();
         Stage stage = (Stage)node.getScene().getWindow();
         Scene scene = (Scene)FXMLLoader.load(getClass().getResource("../view/main/MainMenu.fxml"));     //this is just an example, will change to go to another scene
         stage.setScene(scene);
         stage.show();
    }but now i have another problem, when i click on the button the stage scene is changed, but the scene is transformed to a very small one at the top left (the size seems the same as when i dont put the set width/height on the stage when creating it), the stage size remains the same, and when i resize the window, it gets "repaired"
    the options, i thought on using a pane over the current pane so this way instead of going back would be just removing that new pane, would that work well?
    2. found about languages that is by using <Label text="%myText"/> and java.util.ResourceBundle but don't know how to use it, can someone provide me an example, please?
    3. still haven't looked on it...

  • Question About Java Threads and Blocking

    I'm helping someone rehost a tool from the PC to the Sun. We're using the Netbeans IDE and the Java programming language. I took a Java course several years ago, but need some help with something now. We're developing a front-end GUI using Swing to allow users to select different options to perform their tasks. I have a general question that will apply to all cases where we run an external process from the GUI. We have a "CommandProcessor" class that will call an external process using the "ProcessBuilder" class. I'm including the snippet of code below where this happens. We pass in a string which is the command we want to run. We also instantiate a class called "StreamGobbler" my coworker got off the Internet for redirecting I/O to a message window. I'm also including the "StreamGobbler" class below for reference. Here's the "CommandProcessor" class:
    // Test ProcessBuilder
    public class CommandProcessor {
    public static void Run(String[] cmd) throws Exception {
    System.out.println("inside CommandProcessor.Run function...");
    Process p = new ProcessBuilder(cmd).start();
    StreamGobbler s1 = new StreamGobbler("stdin", p.getInputStream());
    StreamGobbler s2 = new StreamGobbler("stderr", p.getErrorStream());
    s1.start();
    s2.start();
    //p.waitFor();
    System.out.println("Process Returned");
    Here's the "StreamGobbler" class:
    import java.lang.*;
    import java.io.*;
    // Attempt to make the output of the process go to the message window
    // as it is produced rather that waiting for the process to finish
    public class StreamGobbler implements Runnable {
    String name;
    InputStream is;
    Thread thread;
    public StreamGobbler (String name, InputStream is){
    this.name = name;
    this.is = is;
    public void start(){
    thread = new Thread (this);
    thread.start();
    public void run(){
    try{
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    while (true){
    String s = br.readLine();
    if (s == null) break;
    System.out.println(s);
    //messageWindow.writeToMessageArea("[" + name + "]" + s);
    is.close();
    catch(Exception ex){
    System.out.println("Problem reading stream" + name + "...:" + ex);
    ex.printStackTrace();
    The "CommandProcessor" class calls two (2) instances of the "StreamGobbler" class, one for "stdin" and one for "stderr". My coworker discovered these are the 2 I/O descriptors that are needed for the external command we're running in this case. We're actually called the Concurrent Versions System (cvs) command from the GUI. Here's what we need it to do:
    We want to display the output real-time as the external process is executing, but we want to block any actions being performed on the GUI itself until the process finishes. In other words, we want to show the user any generated output from the process, but don't want to alllow them to perform any other actions on the GUI until this process has finished. If we use the "waitFor()" function associated with a process, it blocks all external process output until the process has completed and then spews all the output to the screen all at once. That's NOT what we want. Also, if we don't use the "waitFor()" function, the code just continues on as it should, but we don't know how to block any actions on the GUI until this process has finished. My coworker tried the following code, but it also blocked any output until the process had finished:
    while (s1.thread.isAlive() || s2.thread.isAlive())
    // We really don't do anything here
    I'm pretty sure we have to use threads for the output, but how do we instantly show all output and block any GUI actions?
    Thank you in advance for your help!

    You're talking about a GUI, but there's nothing in that code which is putting events into the GUI update thread. You also say that nothing happens to the GUI until the CommandProcessor.Run() method returns if you wait for the process.
    This implies that you're calling CommandProcessor.Run() in an ActionListener. This will block the GUI thread until it completes.
    I was going to explain what to do, but a quick Google informed me that there's a new class which is designed to help in these situations SwingWorker (or as a [separate library|https://swingworker.dev.java.net/] if you're not up-to-date yet).

  • Question about java-based server app frameworks

    Hello, I am working on a Java applet application and would like to choose a Java-based scalable server framework to use within my applcation. I have found a few like xsocket or QuickServer and have a question about other. And, also, which is the one You may advise? Yours sincerely, Slawek

    For online gaming server. I first heard of xsocket and started using this, but have the problem with NAT. I now know that I need to initiate connections from client behind NAT (server has a public IP) and send messages from server to client within the same connection. I am doing this the following way (as shown in examples- below), but it appears that server receives messages, but client doesnt. I dont listen on any ports in client application and just need to take advantage of the connection initiated (information go from client to server properly).
    Server-
    try{ nbc = pool.getNonBlockingConnection(inetAddress, 8090);
    try{ nbc.write("|01|______|02|______|03|______|04|______|05|______|06|______|07|______|08|______|09|______|10|______"); }catch(Exception ee){}
    }catch(java.io.IOException f){}
    Client-
    public boolean onData(INonBlockingConnection nbc) throws IOException,ClosedChannelException,BufferUnderflowException,MaxReadSizeExceededException{
    String x = nbc.readStringByLength(100);
    System.out.println("S >> C = "+x);

  • Question about dependent projects (and their libraries) in 11g-Oracle team?

    Hello everyone,
    I have a question about dependent projects. An example:
    In JDeveloper 10.1.3.x if you had for instance 2 projects (in a workspace): project 1 has one project library (for instance a log4j library) and project 2 is a very simple webapplication which is dependent on project 1. Project 2 has one class which makes use of log4j.
    This compiles fine, you can run project 2 in oc4j, and the libraries of project 1 (log4j) are added on the classpath and everything works fine. This is great for rapid testing as well as keeping management of libraries to a minimum (only one project where you would update a library e.g.)
    However in 11g this approach seems not to work at all anymore now that weblogic is used, not even when 'export library' is checked in project 1. The library is simply never exported at all - with a noclassdeffound error as result. Is this approach still possible (without having to define multiple deployment profiles), or is this a bug?
    Thanks!
    Martijn
    Edited by: MartijnR on Oct 27, 2008 7:57 AM

    Hi Ron,
    I've tried what you said, indeed in that .beabuild.txt when 'deploy by default' is checked it adds a line like: C:/JDeveloper/mywork/test2/lib/log4j-1.2.14.jar = test2-view-webapp/WEB-INF/lib/log4j-1.2.14.jar
    Which looks fine, except that /web-inf/lib/ is empty. I presume its a sort of mapping to say: Load it like it in WEB-INF/lib? This line is not there when the deploy by default is not checked.
    I modified the TestBean as follows (the method that references Log4j does it thru a Class.forName() now only):
    public String getHelloWorld() {
    try {
    Class clazz = Class.forName("org.apache.log4j.Logger");
    System.out.println(clazz.getName());
    catch(Exception e) {
    e.printStackTrace();
    return "Hello World";
    In both cases with or without line, it throws:
    java.lang.ClassNotFoundException: org.apache.log4j.Logger
         at weblogic.utils.classloaders.GenericClassLoader.findLocalClass(GenericClassLoader.java:283)
         at weblogic.utils.classloaders.GenericClassLoader.findClass(GenericClassLoader.java:256)
         at weblogic.utils.classloaders.ChangeAwareClassLoader.findClass(ChangeAwareClassLoader.java:54)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
         at weblogic.utils.classloaders.GenericClassLoader.loadClass(GenericClassLoader.java:176)
         at weblogic.utils.classloaders.ChangeAwareClassLoader.loadClass(ChangeAwareClassLoader.java:42)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Class.java:169)
         at nl.test.TestBean.getHelloWorld(TestBean.java:15)
    Secondly I added weblogic.xml with your suggested code, in the exploded war this results in a weblogic.xml which looks like:
    <?xml version = '1.0' encoding = 'windows-1252'?>
    <weblogic-web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogic-web-app.xsd" xmlns="http://www.bea.com/ns/weblogic/weblogic-web-app">
    <container-descriptor>
    <prefer-web-inf-classes>true</prefer-web-inf-classes>
    </container-descriptor>
    <jsp-descriptor>
    <debug>true</debug>
    <working-dir>/C:/JDeveloper/mywork/test2/view/classes/.jsps</working-dir>
    <keepgenerated>true</keepgenerated>
    </jsp-descriptor>
    <library-ref>
    <library-name>jstl</library-name>
    <specification-version>1.2</specification-version>
    </library-ref>
    <library-ref>
    <library-name>jsf</library-name>
    <specification-version>1.2</specification-version>
    </library-ref>
    </weblogic-web-app>
    The only thing from me is that container-descriptor tag, the rest is added to it during the deployment. Unfortunately, it still produces the same error. :/ Any clue?

  • ####a question about jdbc driver

    A question about jdbc driver: for Oracle JDBC drivers which will not allow O/R
    tools to access columns over 4 kb. This affects some of the functionality of my
    application.A workaround is to use the my JDBC driver that acts as a wrapper to
    ensure that columns over 4 kb read and persist properly. my JDBC driver determines
    which actual driver to load based on the connection URL. If you pass in a URL
    that contains the string jdbc:oracle:thin, it will know to load oracle.jdbc.driver.OracleDriver.
    If the URL contains the string jdbc:db2, it will know to load COM.ibm.db2.jdbc.net.DB2Driver,
    and so on.
    now i have set CLASSPATH for my jdbc wapper,when I Creating and Configuring a
    JDBC Connection Pool,i have to input my driver name such com.lawrence.driver.....then
    i did,all
    is well,then i restart my WLS,when load config.xml,some errors such as "No registered
    driver accept URL:jdbc:oracle:thin:@localhost:1521:lawrence",if i set driver name
    is oracle.jdbc.driver.OracleDriver,all is good,no any errors.
    I find some questions like:
    1.for WLS8.1 ,it is only find some registed driver?
    2.why it cannot load my driver wapper when it is loading jdbc Connection Pool,but
    when the WLS start is finished, i Creating and Configuring a JDBC Connection Pool
    then it is right?

    my JDBC driver like this:
    public class myDriver implements Driver {
         public static String DB2_DRIVER = "COM.ibm.db2.jdbc.net.DB2Driver";
         public static String DB2_URL = "jdbc:db2:";
         public static String HYPERSONIC_DRIVER = "org.hsqldb.jdbcDriver";
         public static String HYPERSONIC_URL = "jdbc:hsqldb:";
         public static String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
         public static String MYSQL_URL = "jdbc:mysql:";
         public static String ORACLE_DRIVER = "oracle.jdbc.driver.OracleDriver";
         public static String ORACLE_URL = "jdbc:oracle:";
         public static String POSTGRESQL_DRIVER = "org.postgresql.Driver";
         public static String POSTGRESQL_URL = "jdbc:postgresql:";
         public static String SQLSERVER_DRIVER =
              "com.microsoft.jdbc.sqlserver.SQLServerDriver";
         public static String SQLSERVER_URL = "jdbc:microsoft:";
         public boolean acceptsURL(String url) throws SQLException {
              return true;
         public synchronized Connection connect(String url, Properties props)
              throws SQLException {
              if (_driver == null) {
                   Class driverClass = null;
                   try {
                        if (url.startsWith(DB2_URL)) {
                             driverClass = Class.forName(DB2_DRIVER);
                        else if (url.startsWith(HYPERSONIC_URL)) {
                             driverClass = Class.forName(HYPERSONIC_DRIVER);
                        else if (url.startsWith(MYSQL_URL)) {
                             driverClass = Class.forName(MYSQL_DRIVER);
                        else if (url.startsWith(ORACLE_URL)) {
                             driverClass = Class.forName(ORACLE_DRIVER);
                        else if (url.startsWith(POSTGRESQL_URL)) {
                             driverClass = Class.forName(POSTGRESQL_DRIVER);
                        else if (url.startsWith(SQLSERVER_URL)) {
                             driverClass = Class.forName(SQLSERVER_DRIVER);
                        _driver = (Driver)driverClass.newInstance();
                   catch (Exception e) {
                        throw new SQLException(e.getMessage());
              Connection con = _driver.connect(url, props);
              return new myConnection(con);
         public int getMajorVersion() {
              return _driver.getMajorVersion();
         public int getMinorVersion() {
              return _driver.getMinorVersion();
         public DriverPropertyInfo[] getPropertyInfo(String url, Properties props)
              throws SQLException {
              return _driver.getPropertyInfo(url, props);
         public boolean jdbcCompliant() {
              return _driver.jdbcCompliant();
         private Driver _driver;

  • Question about character encoding

    Hey everyone,
    I've been trying to read about character encodings and how Java IO uses them, however, there is something I still don't understand:
    I am trying to read an HTML file encoded in UTF-8 and which contain some Arabic characters.
    I used this code to save it on a file:
    URL u = new URL("http://www.fatafeat.com");    // some Arabic website
    URLConnection connection = u.openConnection();
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("datat.txt"));
    int c;
    while ((c = reader.read())!=-1)
    writer.write(c);However, the output on the file is always "??????"
    I used another version of the code
    URL u = new URL("http://www.fatafeat.com");     //some Arabic website
    URLConnection connection = u.openConnection();
    InputStream reader = connection.getInputStream();
    FileOutputStream writer = new FileOutputStream("datat.txt");
    int c;
    while ((c = reader.read()) != -1)
    writer.write(c);And I get on the file something like this " ÇáæÍíÏÉ áÝä "
    I tried to open the file from a browser using a UTF-8 encoding, but still the same display. What am I missing here? Thanks

    Upon further investigation, my initial hunch appears to be correct. The page in question is not correctly encoded UTF-8, so the Java decoder fails. By default, the java decoder fails silently and replaces malformed input with the character "\uFFFD". If you want more control over the decoding process, you need to read the data as bytes and use the CharsetDecoder class to convert to characters. Here is small example to illustrate:
    import java.io.ByteArrayOutputStream;
    import java.io.CharArrayWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    import java.nio.charset.CoderResult;
    import java.nio.charset.CodingErrorAction;
    public class FatafeatToy3
        private static final Charset UTF8 = Charset.forName("UTF-8");
        private static final Charset DEFAULT_DECODER_CHARSET = UTF8;
        private final CharsetDecoder decoder;
        public FatafeatToy3(final Charset cs)
            this.decoder = cs.newDecoder();
            this.decoder.onMalformedInput(CodingErrorAction.REPORT);
            this.decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
        public FatafeatToy3()
            this(DEFAULT_DECODER_CHARSET);
        public ByteBuffer pageSlurp (URL url) throws IOException
            ByteArrayOutputStream pageBytes = new ByteArrayOutputStream ();
            InputStream is = url.openStream();
            int ch;
            while ((ch = is.read()) != -1)
                pageBytes.write(ch);
            is.close();
            return ByteBuffer.wrap(pageBytes.toByteArray());
        public CoderResult decodeSome(ByteBuffer in, CharBuffer out)
            decoder.reset();
            CoderResult result = decoder.decode(in, out, true);
            if (result.isMalformed())
                System.err.printf("Malformed input detected at pos 0x%x%n", in.position());
            else if (result.isUnmappable())
                System.err.printf("Unmappable input detected at pos 0x%x%n", in.position());
            else if (result.isUnderflow())
                result = decoder.flush(out);
            return result;
        public static void main(String[] args) throws Exception
            FatafeatToy3 ft = new FatafeatToy3();
            ByteBuffer in = ft.pageSlurp(new URL("http://www.fatafeat.com"));
            System.out.printf("Page slurped contains %d bytes%n", in.capacity());
            CharBuffer out = CharBuffer.allocate(1); // one character at a time
            CharArrayWriter pageChars = new CharArrayWriter();
            CoderResult result = CoderResult.UNDERFLOW;
            while ( (! result.isError()) && in.remaining() > 0)
                result = ft.decodeSome(in, out);
                if (result.equals(CoderResult.OVERFLOW))
                    out.flip();
                    pageChars.append(out);
                    out.clear();
    }

  • Quick question about asserts.

    So I am writing an assert statement in my program. and was wondering what I should do if I am going to the next node. should I save the current node to a new variable and then write an assert statement? Or is there a better way to do this.(First time with assert statements :D)
    /**     Return the next element in the iteration
                   @return next element in the iteration
                   @throws NoSuchElementException iteration has no more elements
              public Grade next()
                   Preconditions:
                        hasNext value is true
                   Postconditions:
                        canRemove is true.
                        nodeCounter is incremented.
                        nextNode references the next node
                   /*If hasNext is false then throw exception*/
                   if(!hasNext())
                        throw new NoSuchElementException();
                   if(nextNode == null)
                        nextNode = head;
                   else
                        /* Get the "next node"*/
                        nextNode = nextNode.next;
                   /*Increment the node counter*/
                   nodeCounter++;
                   /*Set canRemove to true */
                   canRemove = true;
                   assert canRemove == true : "canRemove is false";
                   assert nodeCounter >= 0 : "Node counter is negative";
                   *assert nextNode*
                   /*Return grade in nextNode*/
                   return nextNode.data;
              }As you can see I want to write the assert where I have the asterisk marks but not sure how to go around about it. the iterator class variables are
    /* Create a node object */
              private Node nextNode;
              /*Initialize canRemove to false */
              private boolean canRemove = false;
              /* Initialize nodeCounter to 0 */
              private int nodeCounter = 0;Thanks for the help.

    I think you are missing the point of 'asserts'. 'asserts' are not used for flow of control, they are just used for checking integrity. You question "and was wondering what I should do if I am going to the next node" has no relevance as far a 'asserts' are concerned.

  • Question about Runtime.exec

    Rob,
    Thanks for your help.
    I asked a question about a weird Exception on Nov 14, and you told me that I am
    using Runtime.exec to start an external process, and that process is crashing.
    I am a green-hand on Weblogic, and I am trying to enhancing a project developped
    by another person, so I am not familiar with some concepts yet.
    Could you please give me some simple explanation about Runtime.exec and external
    process?
    I found two methods that uses "Runtime" from two classes as following, could you
    help me to see whether or not there is something wrong with the usage of Runtime?
    Thank you very much.
    private int runShellCommand(String command) {
    int exitVal = -1;
    try {
    File runDir = new File(runDirectory);
    String[] env = new String[0];
    Runtime rt = Runtime.getRuntime();
                   double start = System.currentTimeMillis();
    Process proc = rt.exec(command, env, runDir);
    // Capture output in separate thread
    ThreadedStreamReader error = new ThreadedStreamReader(proc.getErrorStream(),
    "ERROR");
    ThreadedStreamReader output = new ThreadedStreamReader(proc.getInputStream(),
    "OUTPUT");
    error.start();
    output.start();
    exitVal = proc.waitFor();
    if (logger.isDebugEnabled()) {
         double runtime = (System.currentTimeMillis() - start) / 1000.0;
         logger.info("run " + runId + " " + command + " finished in " + runtime
    + " seconds");
    } catch (IOException e) {
    logger.fatal("DOE-2 failed \n" + e.getMessage());
    } catch (InterruptedException e) {
    e.printStackTrace();
    return exitVal;
    public static void main(String[] args) throws Exception, InterruptedException
    final Doe2MessageServer server = new Doe2MessageServer();
    while(!connected) {
    Thread.sleep(1000);
    logger.info("Attempting to start JMS service ...");
                   try {
              server.init();
                   } catch (Exception ex) {
    // shutdown hook to close JMS connection
    Runtime.getRuntime().addShutdownHook(
    new Thread() {
    public void run() {
    server.finalize();
    server.receiveMessage();

    Runtime.exec is a J2SE API. It's not really specific to WLS.
    You can read about it here:
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Runtime.html
    It looks like you are starting a JMS Server in a separate process and
    that process is crashing.
    (You could of course just use WLS's JMS Server instead :>)
    -- Rob
    Iris Qu wrote:
    Rob,
    Thanks for your help.
    I asked a question about a weird Exception on Nov 14, and you told me that I am
    using Runtime.exec to start an external process, and that process is crashing.
    I am a green-hand on Weblogic, and I am trying to enhancing a project developped
    by another person, so I am not familiar with some concepts yet.
    Could you please give me some simple explanation about Runtime.exec and external
    process?
    I found two methods that uses "Runtime" from two classes as following, could you
    help me to see whether or not there is something wrong with the usage of Runtime?
    Thank you very much.
    private int runShellCommand(String command) {
    int exitVal = -1;
    try {
    File runDir = new File(runDirectory);
    String[] env = new String[0];
    Runtime rt = Runtime.getRuntime();
                   double start = System.currentTimeMillis();
    Process proc = rt.exec(command, env, runDir);
    // Capture output in separate thread
    ThreadedStreamReader error = new ThreadedStreamReader(proc.getErrorStream(),
    "ERROR");
    ThreadedStreamReader output = new ThreadedStreamReader(proc.getInputStream(),
    "OUTPUT");
    error.start();
    output.start();
    exitVal = proc.waitFor();
    if (logger.isDebugEnabled()) {
         double runtime = (System.currentTimeMillis() - start) / 1000.0;
         logger.info("run " + runId + " " + command + " finished in " + runtime
    + " seconds");
    } catch (IOException e) {
    logger.fatal("DOE-2 failed \n" + e.getMessage());
    } catch (InterruptedException e) {
    e.printStackTrace();
    return exitVal;
    public static void main(String[] args) throws Exception, InterruptedException
    final Doe2MessageServer server = new Doe2MessageServer();
    while(!connected) {
    Thread.sleep(1000);
    logger.info("Attempting to start JMS service ...");
                   try {
              server.init();
                   } catch (Exception ex) {
    // shutdown hook to close JMS connection
    Runtime.getRuntime().addShutdownHook(
    new Thread() {
    public void run() {
    server.finalize();
    server.receiveMessage();

  • A question about AdvancedDatagridColumnGroup

    Hi guys,
         Just a quick question about AdvancedDatagridColumnGroup, is the children property only allowed to have an AdvancedDatagridColumn on it?
    Because what I'm trying to do is in my recursive function I'm trying to create a nested AdvancedDataGridColumnGroup, all good until I set the ADG's groupedColumns to a certain array which is a return array of the recursive function. It throws out an exception something in the groupedValidation function of ADG.
    Here's the code that does that
    var createColumnGroup:Function = function( group:Array, xml:* ) : Array
                                  var ret:Array = new Array;
                                  var colGroup:AdvancedDataGridColumnGroup = newAdvancedDataGridColumnGroup;
                                  for(var index:int = 0; index < 1; ++index){
                                        var parts:Array = String(group[index]).split(DELIMITER);
                                        if(parts.length){
                                              colGroup = new AdvancedDataGridColumnGroup;
                                              colGroup.headerText = parts[0];
                                              colGroup.children = [];
                                              var curHeader:String = parts[0];
                                              parts.splice(0,1);
                                                                                         //this is the part where I'm trying to nest the advancedDataGridColumnGroup
                                                                                         // what's to be replaced in this line to make a valid nest of ADGColumnGroup?
                                              if( parts.length > 0){
                                                    colGroup.children.push( createColumn([parts.join(DELIMITER)], xml));
                                                                                ret.push( colGroup )
                                  return ret;
    and I call it like this
    var gCols:Array = createColumn( colsArr, new XML(_xml.children()[0].toString()));
    adg.groupedColumns = gCols;
    Best Regards,
    jd

    Your problem is you have iDVD 4 or earlier. Such versions ONLY supported internal SuperDrives.
    PatchBurn at http://www.patchburn.de/faq.html may help you.

Maybe you are looking for