How to throw or catch IOException?

Hi,
I am very simply trying to write a method for a class to print the objects info to a file (to test a hw assignment, don't worry, it's not the actual assignment, so I'm not trying to get anyone to do my work for me =D). Unfortunately, since I'm declaring the printwriter outside of any method, I can't figure out how to deal with the "Slider.java:35: unreported exception java.io.IOException; must be caught or declared to be thrown" message the compiler gives.
here is the important part of the code, any suggestions?:
import java.util.*;
import java.io.*;
public class Slider     
//          Instance Data Members     
String slider[][];
int size;
PrintWriter toFile = new PrintWriter(new FileWriter("moves.txt"), true);                    
public Slider(int s)
size = s;
slider = new String[size][size];
iblank = size-1;
jblank = size-1;
for (int i=0; i<size; i++)
for (int j=0; j<size ; j++)
slider[i][j]= Integer.toString(i*size + j + 1);
slider[iblank][jblank] = "";
          public void printToFile()     throws IOException
for (int i=0; i<size ; i++)
for (int j=0; j<size ; j++)
{     toFile.printf("%4s", slider[i][j]);     }
toFile.println();
toFile.println();
}

and format your code properly FFS... and post it between code tags
* prints the matrix to the given PrintWriter
* @param writer PrintWriter - to write to.
public void print(PrintWriter writer) throws IOException {
  for (int i=0; i<size ; i++) {
    for (int j=0; j<size ; j++) {
      writer.printf("%4s", slider[i][j]);
    writer.println();
  toFile.println();
}... and just pass the PrintWriter into the print method

Similar Messages

  • How to throw or catch sql exception for executeReader sql adapter

    Wcf sql adapter was created and executeReader was used.
    When an invalid sql statement was constructed and send it to wcf sql adapter, it will hanging there, and no response. No exception was catched even though send chape  was inside a catch block. How can I catch this kind of exception
    or throw this exception ? I need to give client an exception resposne.
    thanks
    Gary

    I used scope with exception handle which has Exception object type: "System.SystemException".
    I guess this type "System.SystemException" can catch any exception, including sql exception. Maybe I am wrong. I got error from window event:
    A message sent to adapter "WCF-Custom" on send port "WcfSendPort_SqlAdapterBinding_DalCore_Custom" with URI "mssql://shig-quad-2k3e1//DataSourceOne?" is suspended.
     Error details: System.Data.SqlClient.SqlException: Incorrect syntax near '='.
    Server stack trace:
       at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
       at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
       at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
       at System.ServiceModel.Channels.ServiceChannel.EndRequest(IAsyncResult result)
    Exception rethrown at [0]:
       at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
       at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
       at System.ServiceModel.Channels.IRequestChannel.EndRequest(IAsyncResult result)
       at Microsoft.BizTalk.Adapter.Wcf.Runtime.WcfClient`2.RequestCallback(IAsyncResult result)
     MessageId:  {B24EF5B8-298A-4D4F-AA98-5E639361A7DB}
     InstanceID: {F8924129-265B-4652-B20E-8D25F8F20A51}
    If  "System.SystemException" can't catch all exception, which type can catch all exception ? I want to catch all exception in this catch block.
    thanks
    Gary

  • How to Throw/Catch Exceptions in BPM

    Hi All,
    I've seen a couple articles that talk about how to Throw/Catch an execption in a BPM. My question has two parts:
    1) RFC Call: I was able to catch an Fault Message in an exception step when calling an RFC (Synchronous Interface). What I wanted to do is use the fault message (exception) and store it in a DB for later review.
    2) IDOC: I'm sending an IDOC to R3 from a BPM. The send step is enclosed in a block w/ an exception. The send step is throwing an error (IDOC adpater system error), but the exception is never thrown. My question is: when the error occurrs at the adapter level does it still throw an exception in a BPM?
    Thanks for any tip/advice/anything!
    Fernando.

    Hi Fernando,
    1) Define a send step in the exception branch.
    2) If u send a IDoc from R/3 to XI and the IDoc adapter is running to an error of course there cant be an exception in ur business process. Usually the IDoc adapter sends back status back up via ALEAUD. In case of success IDoc should have then '03', if the adapter cannot send anything the IDoc should remain at '39'. U should send a ALEAUD in case of exception of BPM switching to status '40', in case of success to '41'.
    Regards, Udo

  • How to solve java.io.IOException: Corrupt form data: premature ending

    hei evryone!
    Does anyone knows how to solve this bug?
    java.io.IOException: Corrupt form data: premature ending
    Im using Oreilly's cos.jar MultipartRequest
    here is my form :
    <FORM METHOD="POST" NAME="uploadform" action="mbbfile" ENCTYPE="multipart/form-data">
    <TR>
    <TD>Select a File:</TD>
    <TD><INPUT TYPE="FILE" NAME="srcfile" style="width:400px"/></TD>
    </TR>
    <TR><TD><INPUT TYPE="SUBMIT" VALUE="Send"/></TD></TR>
    </FORM>
    HERE IS mbbfile which is a servlet :
    package mbb.servlet;
    import java.io.IOException;
    import java.sql.Connection;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.oreilly.servlet.MultipartRequest;
    import org.jconfig.Configuration;
    import org.jconfig.ConfigurationManager;
    public class MBBFileServlet extends HttpServlet{
         private static final Configuration conf = ConfigurationManager.getConfiguration("ConfigFile");
         public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
              String filePath = conf.getProperty("FilePath", "", "test");
              try{
              MultipartRequest multi = new MultipartRequest(req,filePath,5*1024*1024);
              }catch(Exception e){
                   System.out.println("MBBFileServlet Exception ---> "+e.getMessage());
         public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
              doGet(req,res);
    Sometimes it works meaning the file is uploaded in the directory without any exception, sometimes the file is uploaded but with exception on the log saying "MBBFileServlet Exception ---> Corrupt form data: Premature Ending". and sometimes the files is not uploaded at all and when i check the error is : "MBBFileServlet Exception ---> Corrupt form data: Premature Ending". Can anyone please help me on this matter. Thx!
    Your response would be deeply appreciated.
    br,
    TAC

    Hi all!
    Since I've spent some days now trying to figure out what was wrong with my file upload in Struts 1.1, I would like to share my solution with the rest of you in order to spare you for the same amout of wasted time I've spent :-)
    My platform is Resin 3.0.8 and Struts 1.1. My problem was that JPEG's got corrupted when arriviving at the server. After a few days searching on the net, I tried with a plain servlet and the O'Reilly package, and the app worked perfect.
    Here is my servlet:
    package no.yourcompany.yourapp.servlet;
    import com.oreilly.servlet.multipart.MultipartParser;
    import com.oreilly.servlet.multipart.Part;
    import com.oreilly.servlet.multipart.FilePart;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.ServletException;
    import javax.servlet.ServletContext;
    import javax.servlet.RequestDispatcher;
    import java.io.IOException;
    import java.io.ByteArrayOutputStream;
    public class ImageUpload extends HttpServlet {
    private static final String PAGE_RECEIPT = "/popImageUploadReceipt.do";
    private static final int MAX_FILE_SIZE_IN_BYTES = 10000000; // 10 M
    * Extracts image from request and puts it into person form.
    * @see HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    // custom beans from my project, not defined here
    PersonRegistrationForm personRegistrationForm = null;
    PortraitImage portraitImage = null;
    ByteArrayOutputStream outputStream = null;
    Part currentPart = null;
    FilePart currFilePart = null;
    personRegistrationForm = (PersonRegistrationForm) request.getSession().getAttribute(DsnSessionKeyConstantsIF.KEY_PERSON_FORM);
    portraitImage = personRegistrationForm.getPortraitImage();
    try {
    MultipartParser parser = new MultipartParser(request, MAX_FILE_SIZE_IN_BYTES);
    while ((currentPart = parser.readNextPart()) != null) {
    if (currentPart.isFile()) {
    currFilePart = (FilePart) currentPart;
    outputStream = new ByteArrayOutputStream();
    currFilePart.writeTo(outputStream);
    // portraitImage is just a bean for encapsulating image data, not defined in this posting
    portraitImage.setContentType(currFilePart.getContentType());
    portraitImage.setImageAsByteArray(outputStream.toByteArray());
    portraitImage.setOriginalFileName(currFilePart.getFileName());
    break;
    } // if (currentPart.isFile())
    } // while ((currentPart = parser.readNextPart()) != null)
    } catch (IOException ioe) {
    // noop
    // redirect to receipt page
    ServletContext servletContext = this.getServletContext();
    RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher(PAGE_RECEIPT);
    requestDispatcher.forward(request, response);
    } // doPost
    } // ImageUpload
    AND ADD THIS TO YOUR WEB.XML
    <servlet>
    <servlet-name>ImageUpload</servlet-name>
    <servlet-class>no.yourcompany.yourapp.servlet.ImageUpload</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>ImageUpload</servlet-name>
    <url-pattern>imageUpload.do</url-pattern>
    </servlet-mapping>
    AND THE HTML-FORM IS HERE
    <form action="/yourapp/imageUpload.do" method="post" enctype="multipart/form-data" accept="image/*">
    <p>
    <input type="file" name="portraitImage" />
    </p>
    <p>
    <input type="image" src="/dsn/img/btn_last_bilde.gif" border="0">
    </p>
    </form>

  • How to throw exception in run() method of Runnable?

    Hi, everyone:
    I want to know how to throw exception in run() method of interface Runnable. Since there is no throwable exception declared in run() method of interface Runnable in Java API specification.
    Thanks in advance,
    George

    Thanks, jfbriere.
    I must add though that if your run() methodis
    executed after a call to Thread.start(), then
    it is not a good choice to throw anyRuntimeException
    from the run() method.
    The reason is that the thrown exception won't be
    handled appropriately by a try-catch block.Why do you say that "the thrown exception won't be
    handled appropriately by a try-catch block"? Can you
    explain it in more detail?
    regards,
    George
    Because the other thread runs concurrently with and independently of the parent thread, there's no way you can write a try/catch that will handle the new thread's exception: try {
        myThread.start();
    catch (TheExceptionYouWantToThrowFromRun exc) {
        handle it
    do the next thing This won't work because the parent thread just continues on after myThread.start(). Start() doesn't throw the exception--run() does. And our parent thread here has lost touch with the child thread--it just moves on to "do the next thing."
    Now, you can do some exception handling with ThreadGroup and uncaughtException(), but make sure you understand why the above won't work, in case that was what you were planning to do.

  • [svn] 869: Bug: BLZ-92 - catch IOException and log at the info level to keep from polluting the logs

    Revision: 869
    Author: [email protected]
    Date: 2008-03-19 15:21:25 -0700 (Wed, 19 Mar 2008)
    Log Message:
    Bug: BLZ-92 - catch IOException and log at the info level to keep from polluting the logs
    QA: Yes
    Doc: No
    Details:
    Tomcat 5+ throws a ClientAbortException when it receives a TCP RST while writing a response to a client that has exited. This custom exception extends IOException, and we were only doing lighter INFO-level logging for SocketExceptions so the ClientAbortException was getting past this leading to ERROR level logging. This little tweak will mean less pollution of the server logs during QE load tests.
    Ticket Links:
    http://bugs.adobe.com/jira/browse/BLZ-92
    Modified Paths:
    blazeds/branches/3.0.x/modules/core/src/java/flex/messaging/endpoints/BaseHTTPEndpoint.ja va

    Hi AbhijitRoy2005,
    Other then climbing in the phone and calling the vendor, you could try:
    1. To use a BufferedInputStream to wrap the SocketInputStream before you wrap that in the DataInputStream. So basically:
    DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream());On one of my implementations this made a difference of a factor of 200+! So instead of processing 500 messages per second, I could process 10000 messages per second!
    2. Or to take it to the next level and take a look at using NIO. That is New IO, available since Merlin (Java 1.4). But that would take you way more time then the first attempt.
    The thing addressed by the possible solutions above is the blocking nature of the Stream based socket handling. Using a buffered input stream reads ahead. The NIO thing is all about non-blocking IO, which uses Channels and Buffers instead of Sockets and Streams (note that these are not equivalent!).
    Of course, if you didn't change something in your own code, it might just very well be that the vendor just screwed up his ;)
    Regards,
    Frens

  • Wehre can i find all the throw and catch exceptions

    I havent had much success figuring out which predefined exceptions i should/can use. Can someone please guide me where i can find out what kind of throw and catch exceptions are there in java and how and where can i find them. thanks.

    Read this first: http://java.sun.com/docs/books/jls/second_edition/html/exceptions.doc.html#44044
    You can't find them all anywhere. You'll just encounter them as you use different APIs.
    One of the most basic concepts around exceptions has to do with the difference between checked and unchecked exceptions. Any exception that extends RuntimeException is unchecked. Which means that if you call a method that throws an unchecked exception, you don't have to provide a catch block. These exceptions are usually thrown for things that could be avoided, i.e. programmer error.
    The compiler will require you to have a catch block for all checked exceptions. This means you should take steps in your code to handle them and retry the operation, such as user errors.

  • How the try and catch blocks work?

    For the following section of code from the class QueueInheritanceTest...how the try and catch blocks work?
    The Class...
    public class QueueInheritance extends List {
    public QueueInheritance() { super( "queue" ); }
    public void enqueue( Object o )
    { insertAtBack( o ); }
    public Object dequeue()
    throws EmptyListException { return removeFromFront(); }
    public boolean isEmpty() { return super.isEmpty(); }
    public void print() { super.print(); }
    Testing...
    public class QueueInheritanceTest {
    public static void main( String args[] ){
    QueueInheritance objQueue = new QueueInheritance();
    // Create objects to store in the queue
    Boolean b = Boolean.TRUE;
    Character c = new Character( '$' );
    Integer i = new Integer( 34567 );
    String s = "hello";
    // Use the enqueue method
    objQueue.enqueue( b );
    objQueue.enqueue( c );
    objQueue.enqueue( i );
    objQueue.enqueue( s );
    objQueue.print();
    // Use the dequeue method
    Object removedObj = null;
    try { while ( true ) {
    removedObj = objQueue.dequeue();
    System.out.println(removedObj.toString()+" dequeued" );
    objQueue.print();
    catch ( EmptyListException e ) {
    System.err.println( "\n" + e.toString() );

    If you want a basic introduction to try/catch blocks, read any introductory text or the tutorials on this site.
    Here are some:
    Sun's basic Java tutorial
    Sun's New To Java Center.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns."
    In terms of this particular case, it looks like the code is using an exception being thrown to get out of a loop. IMHO that's bad design -- exceptions should be used for exceptional circumstances, and if you use it to get out of a loop, then you're certain it's going to happen, and that means that it's not exceptional.
    When you post code, please wrap it in  tags so it's legible.

  • How to use Try Catch Block in ABAP Like JAVA

    Hi Experts,
       I am using BAPI to post MIGO in one of my application. If the MIGO is successfully gets posted then BAPI returns no message, but if there is some error in posting then it returns an error message. Now I want to print that error message in catch block by calling method RAISE_ERROR_MESSAGE. How to use try catch block in ABAP. Please suggest with example.
    Thanks and Regards.
    Vaibhav Tiwari.

    Hi Vaibhav
    You may not catch exceptions returned by function module using try endtry block.
    It works well with the exception returned by methods.
    In case of function modules or BAPI what u can do is to check sy-subrc returned and give message accordingly. If it returns a structure like bapireturn then display message returned.
    in case of exception returned by a method,  do it like this...
    data: excep type cx_root.
    data: v_str type string.
    try.
    *any method call or division by zero (for ex)
    catch cx_root into excep.
    endtry.
    if  excep is not initial.
    CALL METHOD   excep->if_message~get_text
      receiving
        RESULT = v_str.
    endif.
    *display the value returned in v_str on screen

  • How to throw custom errors?

    Hi Friends
    How to throw custom errors in APEX?
    For example if I violate a datatype instead of the oracle error i need to get a custom error.
    Thanks
    Nav

    Use raise_application_error - Its built-into the database and not really an APEX specific thing. Google it for more info
    Like so:
    declare
      v_num number;
    begin
      v_num := 1/0;
    exception
      when zero_divide then
        raise_application_error(-20001, 'You tried dividing by zero - luckily I caught it just in time!');
    end;

  • JSF/ADF How to throw UI failure on SQLException?

    I have a button bound to the persistEntity action for a form listed on my page, but there can't be any mistake on whether this get's inserted in the database as it's part of a workflow. Failure was occurring and after checking the logs I found a SQLException for inserting a null value.
    While this is cleared up by more exact control of required fields, I would like to know if there is a way that I can set the persistEntity to cause a noticeable or blocking UI action so that users can't proceed with a workflow when there is an error in the SQL execution.
    Many thanks,
    Raymond

    Oop, sorry. Thanks for the redirect.
    -Raymond
    This post has been made at the following link: JSF/ADF How to throw UI failure on SQLException?

  • How to Throw Music From Your Xperia Tablet S

    If you have any further questions please feel free to ask away. I will do my best to find the answer you are looking for!
    - Patrick
    Solved!
    Go to Solution.

    Sony wants your feedback! http://bit.ly/WcYjMO
    This video will show you how to throw music from your Xperia™Tablet S.
    If you have any further questions please feel free to ask away. I will do my best to find the answer you are looking for!
    - Patrick

  • How can I get/Catch the information about Trigger firing?

    How can I get/Catch the information about Trigger firing?

    I am running one application (backend is Oracle) and have written one trigger, which will insert one row in two tables depending on user event (After Update Trigger).
    I want know last fired Trigger Information.
    Thanks

  • How to throw a CustomException in JSF 2.0 and catch it in the CustomHandler

    Hi,
    I want to throw a custom exception "AppException" in my controller "ManagedBean", where this AppException extends Exception. And to catch it in my CustomExceptionHandler.
    The problem is that when I go to the CustomExceptionHandler, I get the exception as "FacesException" not "AppException "
    <factory>
    <exception-handler-factory>com.web.common.exceptions.DefaultExceptionHandlerFactory</exception-handler-factory>
    </factory>
    public class DefaultExceptionHandlerFactory extends ExceptionHandlerFactory {
    public ExceptionHandler getExceptionHandler() {
    ExceptionHandler eh = new DefaultExceptionHandler(parent.getExceptionHandler());
    return eh;
    public class DefaultExceptionHandler extends ExceptionHandlerWrapper {
    public void handle() throws FacesException {
    Iterator i = getUnhandledExceptionQueuedEvents().iterator();
    while (i.hasNext()) {
    ExceptionQueuedEvent event = (ExceptionQueuedEvent) i.next();
    ExceptionQueuedEventContext context =
    (ExceptionQueuedEventContext)event.getSource();
    //obtain throwable object
    Throwable t = context.getException();
    I need to do some action only when this AppException is thrown
    The only I can do that is through
    if(t.getCause().toString().indexOf("com.exceptions.AppException")!=-1){
    //do some action
    But I want to do something like
    if(t instanceof AppException){
    @ManagedBean(name = "loginController")
    @ViewScoped
    public class LoginController {
    public String login() throws AppException {
    throw new AppException ();
    Any help?
    Edited by: user on Mar 25, 2012 2:47 AM

    For now, just use an object factory, like the builder classes or FXML. If you would prefer that JavaFX implement the Cloneable interface, try filing an issue at Jira.
    It looks like they already considered something, but decided to drop it unless someone expresses a need: http://javafx-jira.kenai.com/browse/RT-137

  • How to throw Exception in Thread.run() method

    I want to throw exception in Thread.run() method. How can I do that ?
    If I try to compile the Code given below, it does not allow me to compile :
    public class ThreadTest {
         public static void main(String[] args) {
         ThreadTest.DyingThread t = new DyingThread();
         t.start();
         static class DyingThread extends Thread {
         public void run() {
         try {
                   //some code that may throw some exception here
              } catch (Exception e) {
              throw e;//Want to throw(pass) exception to caller
    }

    (a) in JDK 1.4+, wrap your exception in RuntimeException:
    catch (Exception e)
    throw new RuntimeException(e);
    [this exception will be caught by ThreadGroup.uncaughtException() of this thread's parent thread group]
    In earlier JDKs, use your own wrapping unchecked exception class.
    (b) if you know what you are doing, you can make any Java method throw any exception using Thread.stop(Throwable) regardless of what it declares in its "throws" declaration.

Maybe you are looking for

  • Pros and cons of various dual boot  and virtual options?

    I have purchased a 500 GB hdd 8 GB RAM Macbook Air with the intent of being able to run a few PC programs (i.e., no Mac versions) a few times a week, both of which are radiology image viewing programs.  I can cover other programs with Mac software ve

  • Any "Best Practice" regarding use of zfs in LDOM with zones

    I have 3 different networks and I want to create a guest-domain for each of the three networks on the same control domain. Inside each guest-domain, I want to create 3 zones. To make it easy to handle growth and also make the zones more portable, I w

  • Why Does Shockwave Flash Keeps Crashing In Firefox?

    I've been using adobe shockwave flash player with no problem for the last six years. Recently I brought a new computer, windows vista and downloaded the adobe reader and shockwave player. Everytime I go to watch a video on the internet flash player w

  • Can Ajax concept apply in SAP R/3?

    Dear All, The term Ajax is used to describe a set of technologies that allow browsers to provide users with a more natural browsing experience. Before Ajax, Web sites forced their users into the submit/wait/redisplay paradigm, where the users' action

  • SRGB or Adobe RGB for stills?

    When preparing photos in PS to bring into PP, does the color space matter? 1. For HD video which color space should I use? 2. For 4K video which color space should I use? Thanks.