Code in main does not require catch, but code in constructor does

this is the original program, its all in main. i took all the code out of main and put it in a constructor to make it more usable, and started making the necessary adjustments. i eventually got it to work but i had to catch exceptions EVERYWHERE. why does this code not require so many exceptions when the code is in main?
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class MainClass {
  public static void main(String args[]) throws Exception {
    URL u = new URL("");
    URLConnection uc = u.openConnection();
    String contentType = uc.getContentType();
    int contentLength = uc.getContentLength();
     // ||
    if (contentLength == -1) {
      throw new IOException("Error: No File Found.");
    InputStream raw = uc.getInputStream();
    InputStream in = new BufferedInputStream(raw);
    byte[] data = new byte[contentLength];
    int bytesRead = 0;
    int offset = 0;
    while (offset < contentLength) {
      bytesRead = in.read(data, offset, data.length - offset);
      if (bytesRead == -1)
        break;
      offset += bytesRead;
    in.close();
    if (offset != contentLength) {
      throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
     String dirText = "text";
     String dirTarget = "target";
     String filename = u.getFile().substring(u.getFile().lastIndexOf('/') + 1);
     String dirAndFile;
     // determine weather the file is a target or is to be parsed for more files
     if(contentType.startsWith("text/")) {
          dirAndFile = dirText + "\\" + filename;
     else {
          dirAndFile = dirTarget + "\\" + filename;
    FileOutputStream out = new FileOutputStream(dirAndFile);
    out.write(data);
    out.flush();
    out.close();
}Edited by: chopficaro on May 1, 2010 8:15 AM

ok but still, why do i not have to catch all these exceptions when the code is in main rather than a constructor? heres the code after i put it in the constructor:
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.MalformedURLException;
public class MainClass {
     public static void main(String args[]) throws Exception
          MainClass mc = new MainClass("http://www.google.com/intl/en_ALL/images/logo.gif");
     MainClass(String addr)
          URL u = null;
          try
               u = new URL(addr);
          catch (MalformedURLException e)
               // Print out the exception that occurred
               System.out.println("Invalid URL "+addr+": "+e.getMessage());
          URLConnection uc = null;
          try
               uc = u.openConnection();
          catch (IOException e)
               // Print out the exception that occurred
               System.out.println("Unable to create "+addr+": "+e.getMessage());
          String contentType = uc.getContentType();
          int contentLength = uc.getContentLength();
          if (contentLength == -1)
               System.out.println("no file");//throw new IOException("Error: No File Found.");
          InputStream raw=null;
          InputStream in=null;
          try
               raw = uc.getInputStream();
               in = new BufferedInputStream(raw);
          catch (IOException e)
          // Print out the exception that occurred
          System.out.println("bad input stream "+e.getMessage());
          byte[] data = new byte[contentLength];
          int bytesRead = 0;
          int offset = 0;
          while (offset < contentLength)
               try
                    bytesRead = in.read(data, offset, data.length - offset);
               catch (IOException e)
                    // Print out the exception that occurred
                    System.out.println(e.getMessage());
               if (bytesRead == -1)
               break;
               offset += bytesRead;
          try
               in.close();
          catch (IOException e)
               // Print out the exception that occurred
               System.out.println(e.getMessage());
          if (offset != contentLength)
               System.out.println("didnt read enough bytes"); //throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
          String dirText = "text";
          String dirTarget = "target";
          try
               String filename = u.getFile().substring(u.getFile().lastIndexOf('/') + 1);
               String dirAndFile;
               // determine weather the file is a target or is to be parsed for more files
               if(contentType.startsWith("text/"))
                    dirAndFile = dirText + "\\" + filename;
               else
                    dirAndFile = dirTarget + "\\" + filename;
               FileOutputStream out = new FileOutputStream(dirAndFile);
               out.write(data);
               out.flush();
               out.close();
          catch (IOException e)
               // Print out the exception that occurred
               System.out.println(e.getMessage());
}

Similar Messages

  • I am having trouble using reverb of any kind; it does not sound natural, but rather "pixilated." Does anyone have any ideas for a solution? I have used Silververb and Space Designer and am having the same problem...

    I am using Logic Pro 9 with two MXL 990 microphones in my piano and a Rode NT1A for vocals. I have tried recording with added reverb and keeping getting not a natural reverb sound, but a rather "pixilated" one that does not sound natural. Does anyone have any ideas on how to solve this issue? I have tried using Silververb and Space Designer, and both result in the same problems. Thank you!

    This is asking for the impossible! It does not sound natural because maybe it isn't and in judging so whats your reference anyway. If you are in dire need of some natural sounding room you can go and record it yourself. But even then, the chances that it sounds like you imagined it, are very slim.
    There are very decent sounding reverberation plugins, based on artificial reverb generators or convolution-style, the last one is said to sound more 'natural' then the first one. Be it as it maybe, it really is like cooking food. You got all the ingredients for this delicious taste at hand and believe it or not to reach a satisfying result this is not enough, because if you do not mix the ingredients in the right proportion you will end up with a different dish you thought you'll get. This is exactly the same when one would mix audio, I dare say.
    So treat yourself to some good ingredients and the rest is up to you, namely: taste and experience!
    And looking at some of my past music productions I always find the same plugins for the 'ambient' task:
    Altiverb by Audio Ease when I have acoustic ensembles (classical music mostly), the Sony Oxford Reverb in studio productions, Bricasti when I have to deal with drums and MMultiBandReverb from MeldaProduction for all-round stuff. Thats the base I start from, after that I can end up with dozen Reverb plugins which basically all are doing the same thing but just in a tiny different way.

  • Is there a mobile phone that can sync with ical, but does not require a data plan?

    Is there a mobile phone that can sync with ical, but does not require a data plan?

    Thanks for the reply.  I already have this info, but have spent several hours trying to cross reference with the product descriptions and the different carriers websites.  I was hoping there was an easier way.
    John Maisey wrote:
    Hi,
    You cakn sync many phones using iSync. See here: http://support.apple.com/kb/ht2824
    Best wishes
    John M

  • TS1424 I download movies and when I reach the full size, like 4.01 GB for an HD movie, it does not say "done" but Error Code= -36

    I download movies and when I reach the full size, like 4.01 GB for an HD movie, it does not say "done" but Error Code= -36

    What do you think about turning File Vault off?
    I'd first make a copy or backup of that Home folder first, then I'd never use Filevault again.
    Is it possible the disk could be failing but Disk Utility not pick anything up?
    Yes, DU just checks Directory structure, and not all that well at that, it is possible that there are bad blocks/sectors on the HD right where that Home Folder is located.
    And finally, where is a good place to find interpretations of those cryptic error codes?!
    For error -36, might try this...
    http://docs.info.apple.com/article.html?artnum=301580
    Well, in pure Apple File System talk... -36 ioErr I/O error (bummers)
    Not very helpful, but generally means a Drive quit being Readable or Writable since starting the operation...
    http://fuzzy.wordpress.com/2006/12/10/ioerror-36/
    Terminal for one...
    Find error code...
    /usr/bin/grep "36" /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/CarbonC ore.framework/Headers/MacErrors.h
    Or open this file in Text Edit if you have it...
    System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/CarbonCor e.framework/Versions/A/Headers/MacErrors.h

  • Sms code for verification does not reach to my mobile. ? i can not access my e-mail because of code that does not sent right now. code that related to my alternated e-mail was sent , but not to mobile

    sms code for verification does not reach to my mobile. ? i can not access my e-mail because of code that does not sent right now. code that related to my alternated e-mail was sent , but not to mobile

    Bugzilla is not the place for this sort of problem. Forwarded this post to the relevant team.

  • My service provider's SMTP does not require a password but the option "non" does not appear on the IPOD Touch 5th gen. Fix?

    I have relay.skynet.be as my outgoing server and it does not require/allow password protection. When configuring mail on the Ipod the option of "non" is not given for the outgoing server. Is this a skynet issue or is there an Ipod solution?

    Google for:
    setup XX email on iphone
    to see if ony of the returned sites help.
    XX is you email provider.

  • Tax code does not exist in company code Error in FBCJ

    Dear Sir,
    I want to post a document using business transaction Expenses in Cash Book.
    In this case entry will be posted to the GL account which are tax relevant.
    Necessary configuration for Business Transactions in FBCJ2 have been done.
    even The Tax code is assigned to Company code in MM (SM30 > J_1ICONDTAX)
    It is observed that the transection calculates Tax and geting saved (The indecator becomes Yellow)
    But at the time of posting entry to FBCJ Cash Book System throws error
    "Tax code ZM does not exist in company code 1000"
    I am using the same tax code namely "ZM" in other transactions such as F-02
    where it is working fine and does not throw any error.
    Please take me to step by step configuration if the same needs to be configured @ FV12
    Regards & Thanks in anticipation
    Chirag Shah

    Dear Sir,
    I have checked @ FV12 and found that the condition record is already exist with the Key combination of the referred tax code namely ZM.
    But i could not find how to check the WEF date.
    Even I tried Creating new condition record through FV11 but even there i could not find how do I create a condition WEF 1.4.2011 (The first date of Fiscal Year)
    Kindly Guide
    Regards & Thanks in anticipation
    Chirag Shah

  • TS1398 After updating to ios 6 my iphone 4 would no longer connect to my home wifi. At work we have a free wifi connection that does not require a password. However my wifi at home is password protected. I have the right password. It works on my ipod touc

    After updating my iphone 4 with the ios 6 update. My iphone would no longer connect to my home wifi that is password protected. I know that I have the right password entered in. At work we have a free wifi connection that does not require a password and I can connect no problem to it. My ipod touch has no problem connecting to my home wifi. It is a 3rd gen ipod and does not have the ios 6 update on it. Please help!

    I'm having the same issues. Started when I upgraded iphone 4S and ipad1 to 5.1.1. Wife's iphone 4g on 4.4.2 has been ok. I've forgot the network on both devices and restored the iphone, none of which changed the issue. I've upgraded to ios 6 on the iphone 4s, problem still persists.
         One thing that will help for a time: go to your router and change the wireless control channel. When I first did this I got full connectivity for about 48 hours... and now the problem is back. I'm now changing the wireless control channel every 12 hours, which is a pain but at least keeps me connected. I've tried a few other solutions that are out there and that has been the best one so far.
         to do this on a motorola router: type 192.168.0.1 in your address bar.
    username: admin and password:motorola if you have not changed the factory defaults.
    Click on the word "wireless" and look for the "control channel" field. This may be set to auto or to 1, try changing it to 6 or 11 (preferred) or any other channel.
    The control channel can cause static in the wireless system IF there are several networks nearby that are on the default setup.
    There is a fair bit of buzz about this issue out there, some other things I've seen:
    This is a hardware issue. Go to the store and have your wifi antenna checked, some users reporting that they get free replacement devices.
    Check against other wifi networks that require a password (this is next for me). Logon to those networks and surf until your wifi stops. If your wifi connects to the internet but stops responding, then this is a software (or hardware) issue and apple needs to step up. Some are claiming this to be the case.
    IF you connect and stay connected/on the internet on another password protected wifi, then the issue is with your router. this is where things get cute.
    Comcast may tell you to update your firmware. Motorola may tell you that your cable provider is the only one who can push through firmware updates. Comcast may tell you that you are not in an area that is being updated. It's unclear if they say that to all customers, or just those who have purchased cable modems and aren't renting them from comcast.
    Good luck, more to come if I figure out anything else, and please post any solutions you may find.

  • Where can I get a digital certifcate that does not require a USB key?

    Where can I get a digital certificate that I can use with Adobe Acrobat that does not require a USB hardware key?
    I have been able to sign PDF documents with Adobe Acrobat versions 6 and 9 with my code signing certificate. When I use my code signing certificate Acrobat says the validity of the document certification is unknown.

    Per existing standards (RFC 5280) code signing certificates may not be used for signing. For a number of versions Acrobat had a bug that ignored this requirement. Starting with version 11.0.07 Acrobat (and Reader) enforces this requirement.

  • Tax code does not exist for jurisdiction code  in creating purchase order

    Hello Experts,
    After doing a technical upgrade from 4.6 C to ECC EHP 4 , while creating a PO , we are facing an error that
    "Tax code A0  does not exist for jurisdiction code  4318702801".  for one plant  .
    But in 4.6C, there is no problem with the field jurisdiction code in Invoice tab at the PO item level data. it allowed to create PO even with out entering jurisdiction code .
    we have  assigned jurisdiction code to   the particular plant  through config settings in T code OX10.And also we have verified the G/L account properties for the material used in creaton of PO. it will allow all tax codes.
    But still we are facing the same error.
    Please suggest where to establish linkgae betweeen Tax code and jurisdiction code at  customize / config level.
    it is very high priority issue . please suggest
    regards,
    Tulasi

    Hi,
    As  tax jurisdiction code is assigned to your plant on OX10 t.code and cross check  Tax code  declared as input tax & assigned to company code in t.code: OBCL with tjurisdiction code.
    Now double cross check Tax code created (FTXP)for your country with jurisdiction code.
    Also check table A003 for entry of tax code and company code.
    Regards,
    Biju K

  • G/L account does not exist in company code

    Hi,
    When posting a GR (movement type 101) via MIGO one of my users ran into above error message:
    G/L account 300000 does not exist in company code PFNA.
    I first checked the material valuation and found out that it was incorrect.
    After the material valuation in the master data was adjusted, I executed MIGO again, but I still end up with the same error message: G/L account 300000 does not exist in company code PFNA.
    Tried to add a line to the PO, even created a new PO for the same material / plant: same result.
    Did the simulation in OMWB for material / plant combination:
    - old valuation class: 300000
    - new valuation class: 340000
    Also in OBYC same GL accounts are related to BSX. Another GL account 440000 can be found in WRX (but is of no impact here).
    So it seems like although material master was updated, still the old valuation class is getting called to determine the account.
    Anyone any ideas?
    Thanks in advance!
    Geert

    Hi Amol,
    Thanks again for your input!
    Meanwhile I have received the material via MB1A movement type 202 and put the PO item on Delivery Completed.
    This was really a system bug as I had another PO and material (100% same situation including error message) for which the MIGO worked after the valuation class got changed in the material master.
    Thanks a lot for your help!
    Regards,
    Geert

  • Ipad displays "ipad is disabled connect to itunes", I have tried putting the ipad into recovery mode and then restoring but that does not work. I have also tried doing a hard reset of the ipad and that does not work either. Any ideas?

    Ipad displays “ipad is disabled connect to itunes”, I have tried putting the ipad into recovery mode and then restoring but that does not work. I have also tried doing a hard reset of the ipad and that does not work either. Any ideas?
    My son let one of his friends use his ipad. The next time he tired to use it he could not get it unlocked, I tired to unlock it but it kept telling me that I had the wrong pass code. With out me knowing my son continued to tire until it completely disabled it self.

    How can I unlock my iPad if I forgot the passcode?
    http://www.everymac.com/systems/apple/ipad/ipad-troubleshooting-repair-faq/ipad- how-to-unlock-open-forgot-code-passcode-password-login.html
    iOS: Device disabled after entering wrong passcode
    http://support.apple.com/kb/ht1212
    How can I unlock my iPad if I forgot the passcode?
    http://tinyurl.com/7ndy8tb
    How to Reset a Forgotten Password for an iOS Device
    http://www.wikihow.com/Reset-a-Forgotten-Password-for-an-iOS-Device
    Using iPhone/iPad Recovery Mode
    http://ipod.about.com/od/iphonetroubleshooting/a/Iphone-Recovery-Mode.htm
    You may have to do this several times.
    Saw this solution on another post about an iPad in a school environment. Might work on your iPad so you won't lose everything.
    ~~~~~~~~~~~~~
    ‘iPad is disabled’ fix without resetting using iTunes
    Today I met my match with an iPad that had a passcode entered too many times, resulting in it displaying the message ‘iPad is disabled – Connect to iTunes’. This was a student iPad and since they use Notability for most of their work there was a chance that her files were not all backed up to the cloud. I really wanted to just re-activate the iPad instead of totally resetting it back to our default image.
    I reached out to my PLN on Twitter and had some help from a few people through retweets and a couple of clarification tweets. I love that so many are willing to help out so quickly. Through this I also learned that I look like Lt. Riker from Star Trek (thanks @FillineMachine).
    Through some trial and error (and a little sheer luck), I was able to reactivate the iPad without loosing any data. Note, this will only work on the computer it last synced with. Here’s how:
    1. Configurator is useless in reactivating a locked iPad. You will only be able to completely reformat the iPad using Configurator. If that’s ok with you, go for it – otherwise don’t waste your time trying to figure it out.
    2. Open iTunes with the iPad disconnected.
    3. Connect the iPad to the computer and wait for it to show up in the devices section in iTunes.
    4. Click on the iPad name when it appears and you will be given the option to restore a backup or setup as a new iPad (since it is locked).
    5. Click ‘Setup as new iPad’ and then click restore.
    6. The iPad will start backing up before it does the full restore and sync. CANCEL THE BACKUP IMMEDIATELY. You do this by clicking the small x in the status window in iTunes.
    7. When the backup cancels, it immediately starts syncing – cancel this as well using the same small x in the iTunes status window.
    8. The first stage in the restore process unlocks the iPad, you are basically just canceling out the restore process as soon as it reactivates the iPad.
    If done correctly, you will experience no data loss and the result will be a reactivated iPad. I have now tried this with about 5 iPads that were locked identically by students and each time it worked like a charm.
    ~~~~~~~~~~~~~
    Try it and good luck. You have nothing more to lose if it doesn't work for you.
     Cheers, Tom

  • Trivia game that does NOT require data

    looking for a trivia game that does not require an Internet connection. We are going camping and like to play a trivia game around the camp fire, but there is no cell service or data or wifi. We have used Mr Trivia for the last couple years but have ran out of new questions. Looking for something simular in function. Most of what I've tryed does not funtion without running data.
    ipad, iphone or pod (mutiple generations)
    thanks

    dalewren wrote:
    Are there any carriers that allow this?
    Not that I'm aware of. In fact, many carriers, if they detect an iPhone on their network without a data plan, will either bill you for such or cancel your service.

  • SAP Error "Trader does not exist for company code"

    Good Day,
    In SAP, we have multiple users in the role of trader. However, for one user, he keeps getting the message "Trade <name> does not exist for company code <code>" when he hits enter on the first screen of transaction TX01.
    We have copied the profile of another user who is not getting that error, but still he keeps getting the error. What else should we check apart from the profile?
    Thanks
    VC

    Thanks all, but i solved the problem.

  • Tax code V0 does not exist for jurisdiction code IN00 Message no. FF718

    Hi,
    i have configured as per suggestion in message as well as assign Jurisidiction code in taxcode in FTXP, but when i try to create PO with tax code V0 and jurisdiction code IN00 then we are facing error "Tax code V0 does not exist for jurisdiction code IN00 Message no. FF718"
    please advice me and help to resolve this issue is any config missing pls guide me.
    Thanks
    Best regards
    Shital D

    Please check this answered link:
    Juristiction code - Error: FF718
    Cost centre
    Edited by: Afshad Irani on Jun 22, 2010 7:05 PM

Maybe you are looking for