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.

Similar Messages

  • Try and Catch don't work on powershell module

    Hi everyone,
    i'm tring to create a module with a try and catch, but when i call it, the block of expetion doesn't work as i expect, while if i use the code as a function only it works...
    Here the code
    function global:Process{
    param([string]$Process)
    ######################################MAIL################################
    function global:SendMail(){
    param([string]$Services)
    $Dest="xxx"
    $smtpServer = "xxx"
    $msg = new-object Net.Mail.MailMessage
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $msg.From = "xxx"
    $msg.To.Add($Dest)
    $msg.Subject = "Notification about $Services activity"
    $msg.Body = "xxxx"
    $smtp.Send($msg)
    switch($Process){
    "DSP"{
    if((Get-Service Fax | ForEach-Object {$_.Status}) -eq "Stopped"){
    try
    start-service Fax -ea Stop
    catch
    if ( $error[0].Exception -match "Microsoft.PowerShell.Commands.ServiceCommandException")
    $error[0].Exception | Out-File C:\log.txt
    $SendMail $Process
    elseif((Get-Service Fax | ForEach-Object {$_.Status}) -eq "Running"){
    Stop-Service Fax}
    Export-ModuleMember -Function Process
    Could you help me? Thanks so much
    Cristian

    Hello,
    You should ask in the
    Windows PowerShell forum.
    Karl
    When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answer.
    My Blog: Unlock PowerShell
    My Book:
    Windows PowerShell 2.0 Bible
    My E-mail: -join ('6F6C646B61726C406F75746C6F6F6B2E636F6D'-split'(?<=\G.{2})'|%{if($_){[char][int]"0x$_"}})

  • I recently did the iOS 7.0.2 update, now I'm unable to purchase apps. "App could not be purchased at this time. Please try again later. ". I have tried a few of the suggestions and nothing has worked. Reset,change auto lock time on main screen, now what??

    I recently did the iOS 7.0.2 update, now I'm unable to purchase apps. "App could not be purchased at this time. Please try again later. ". I have tried a few of the suggestions and nothing has worked. Reset,change auto lock time on main screen, change language setting. Now what???

    This sorted it for me:
    Backup your iPhone to iCloud (I believe backing up to iTunes will work too). Now go to "Settings --> General --> Reset --> Erase All Content and Settings" to completely restore your iPhone to factory settings. Assuming you've backed up to iCloud, you'll be asked when setting up your iPhone if you want to restore from an iCloud backup. Choose that option and once your iPhone has restored itself from your backup, this annoying problem will finally be gone! (was for me anyway).
    To restore from an iTunes backup, connect your iPhone to your computer, load iTunes. Click the File menu and select Devices > Restore from Back up.

  • TS1440 A flashing question mark appeared when I started my MacBook Pro, I've tried all the suggestions and nothing has worked. How can I back up my current files so I can reinstall Mavericks?

    I recently did a manual reboot after my MacBook Pro had frozen, and instead of the usual Apple and loading icon, it gave me the flashing question mark on a folder, which I've never encountered before. I looked up some possible reasons on my PC, and after reading that there's a problem with my HD I tried looking up how to back up my files so that I can do a clean reinstall of Yosemite (latest ver.). However, I've never used anything like Time Machine or anything else that could back up all my files, so it didn't sound like I could do anything about that at this point. I've also tried going into Disk Utility and attempting to repair the disk image. There was only 2 available, disk0 and the base system. I verified the base system, and told me there was nothing wrong (it didn't give me the option to repair anything either, on both available options). I don't think this is the right thing though, since my drive was called MacBook Pro HD. So basically this is the point I'm at now. Is there anything I can do that will repair my HD without erasing all my files?

    I've tried all the suggestions and nothing has worked.
    I verified the base system, and told me there was nothing wrong
    Hold the option key on boot to see if you can select your Macintosh HD.
    A flashing question mark or globe appears when you start your Mac - Apple Support
    You can boot into Recovery and re-install the OS X on top of what you have.  It will preserve your user data.
    command R on boot.
    Recovery  http://support.apple.com/kb/HT4718

  • Hi i want to send an ipad of a gift to a friend in italy, can it be done? will the wifi and 3g still work? also how does it work for a warrenty?

    hi i want to send an ipad of a gift to a friend in italy, can it be done? will the wifi and 3g still work? also how does it work for a warrenty?

    WiFi will work, cellular will work but they may not be able to access LTE, they will have to send it back to you for the warranty work.

  • I cant get the font to work on a picture in Photoshop, I have watched at least 12 how to videos and it wont work, Help

    I cant get the font to work on a picture in Photoshop, I have watched at least 12 how to videos and it wont work, Help

    Could you capture your screen and post it. Have the layers panel open and any layers that are collapsed, expanded. We will need to see the entire screen, as some information in the tab is important as well.

  • I have been trying for three days to try and get this working , and tried a few of the forum suggestions already and this is just to try them ... so glad i haven't pais anything yet . i get the signed out loop no matter what i try

    i have been trying for three days to try and get this working , and tried a few of the forum suggestions already and this is just to try them ... so glad i haven't pais anything yet . i get the signed out loop no matter what i try

    What have you been trying for three days to try and get this working???
    Supply pertinent information for quicker answers
    The more information you supply about your situation, the better equipped other community members will be to answer. Consider including the following in your question:
    Adobe product and version number
    Operating system and version number
    The full text of any error message(s)
    What you were doing when the problem occurred
    Screenshots of the problem
    Computer hardware, such as CPU; GPU; amount of RAM; etc.

  • I have recently downloaded Bootcamp onto my MBP.  However, when i try to expand it from "downloads" it says "Unable to expand BootCamp5.0.5033 into downloads.  Error 2-no such file or directory.  I have tried changing the partition and Zipeg. didnt work

    I have recently downloaded Bootcamp onto my MBP.  However, when i try to expand it from "downloads" it says "Unable to expand BootCamp5.0.5033 into downloads.  Error 2-no such file or directory.  I have tried changing the partition and Zipeg. didnt work.

    You need to read and follow the Boot Camp instructions. Boot Camp Assistant is already on your computer in the utilities forderf. You run Boot Camp Assistant. Part of the process is to to then download the Windows Support software. This download is then installed from within Windows.
    There is no Boot Camp download that needs to be installed or unzipped from within OSx which you seem to be doing.

  • When I try to start up my macbook, it makes the startup noise, but won't go any farther than the white/grey screen. I've tried the commands and nothing has worked. Please help

    When I try to start up my macbook, it makes the startup noise, but won't go any farther than the white/grey screen. I've tried the commands and nothing has worked. Please help

    Hey marleyrose,
    Thanks for the question. I understand that you are experiencing issues with your MacBook. The following resource may provide a solution:
    Mac OS X: Gray screen appears during startup
    http://support.apple.com/kb/ts2570
    Thanks,
    Matt M.

  • Hello. Tell how to enter the program and to start working in it.  I paid, loaded and installed the program Photoshop CC

    help please to start working... with English at me in any way without translator... if somebody can explain in Russian as to start the program, I will be very grateful
    Tell how to enter the program and to start working in it.  I paid, loaded and installed the program Photoshop CC

    Online Chat Now button near the bottom for Activation and Deactivation problems may help
    http://helpx.adobe.com/x-productkb/policy-pricing/activation-deactivation-products.html

  • Repost as question for points: What did I do wrong? (Try and Catch program)

    This has to be a try and catch program.
    This is the given output sample:
    OUTPUT SAMPLE #2 for input.txt: 12345 222256 -3 123 -56784 555557 6345678 x x x 81234 121212 x x 123434 x x 1009098 2099
    Please input the name of the file to be opened: input.txt
    For number 12345 the sum of digits is: 15
    For number 222256 the sum of digits is: 19
    Found an integer (-3), but it is negative. Will ignore!
    For number 123 the sum of digits is: 6
    Found an integer (-56784), but it is negative. Will ignore!
    For number 555557 the sum of digits is: 32
    For number 6345678 the sum of digits is: 39
    For number 81234 the sum of digits is: 18
    For number 121212 the sum of digits is: 9
    For number 123434 the sum of digits is: 17
    For number 1009098 the sum of digits is: 27
    For number 2099 the sum of digits is: 20
    Here is what I have so far.
    import java.util.Scanner;
      import java.io.*;// FileNotFoundException
    public class Assignment3b {
      public static void main (String[]args){
        Boolean fileOpened = true; 
        String fileName;
        int n,mod=0,sum=0,t=0;
        Scanner inputFile = new Scanner(System.in);
        System.out.print("Please input the name of the file to be opened: ");
        fileName = inputFile.nextLine();
        System.out.println();
        try {
                inputFile = new Scanner(new File(fileName));
            catch (FileNotFoundException e) {
                System.out.println("--- File Not Found! ---");
                fileOpened = false;
            if (fileOpened) {
              while (inputFile.hasNext()){
                if (inputFile.hasNextInt()){
                  n = inputFile.nextInt();
                  t=n;
                  while(n>0){
                    mod = n % 10;
                    sum = mod + sum;
                    n = n/10;
                  System.out.println ("For number " + t + " the sum of digits is : " + sum);
                  mod = 0;
                  sum = 0;
                  while (n<0) {
                    System.out.println ("Found an integer (" + t + "), but it negative. Will ignore!");
                    inputFile.next();
                    n = inputFile.nextInt();
                else {
                  inputFile.next();
    }Everything seems to work fine until, it is time to deal with negative numbers. How can I fix this. Please put your reply in layman's terms to the best of your ability.
    Thanks and God Bless.

    // COSC 236                                Assignment # 3
    // YOUR NAME: Anson Castelino
    // DUE-DATE:
    // PROGRAM-NAME: Assignment # 3 Prt2
    //import packages
      import java.util.Scanner;
      import java.io.*;// FileNotFoundException
    public class Assignment3b {
      public static void main (String[]args){
        Boolean fileOpened = true; 
        String fileName;
        int n,mod=0,sum=0,t=0;
        Scanner inputFile = new Scanner(System.in);
        System.out.print("Please input the name of the file to be opened: ");
        fileName = inputFile.nextLine();
        System.out.println();
        try {
                inputFile = new Scanner(new File(fileName));
            catch (FileNotFoundException e) {
                System.out.println("--- File Not Found! ---");
                fileOpened = false;
            if (fileOpened) {
              while (inputFile.hasNext()){
                if (inputFile.hasNextInt()){
                  n = inputFile.nextInt();
                  t=n;
                  while(n>0){
                    mod = n % 10;
                    sum = mod + sum;
                    n = n/10;
                  System.out.println ("For number " + t + " the sum of digits is : " + sum);
                  mod = 0;
                  sum = 0;
                  if (n<0) {
                    System.out.println ("Found an integer (" + t + "), but it is negative. Will ignore!");
                    inputFile.next();
                  inputFile.hasNext();
                else {
                  inputFile.next();
    }Updated code.
    current output is as follows:
    Please input the name of the file to be opened: [DrJava Input Box]
    For number 12345 the sum of digits is : 15
    For number 222256 the sum of digits is : 19
    For number -3 the sum of digits is : 0 <-------- this part is not suppose to be here.
    Found an integer (-3), but it is negative. Will ignore!
    For number -56784 the sum of digits is : 0 <-------- this part is not suppose to be here.
    Found an integer (-56784), but it is negative. Will ignore!
    For number 6345678 the sum of digits is : 39
    For number 81234 the sum of digits is : 18
    For number 121212 the sum of digits is : 9
    For number 123434 the sum of digits is : 17
    For number 1009098 the sum of digits is : 27
    For number 2099 the sum of digits is : 20
    >

  • Textfields Try and Catch

    Hi All, just a quick question really...
    Was wondering how I would go about checking user inputs into textfields?
    For example if the user enters the number 12 and you're only allowed to enter numbers between 1-10 how could I send a pop up error message to say "You can only enter numbers between 1-10"
    A way I thought about doing this was with a try and catch method, there could be another way of doing this, all other methods appreciated too.
    function captureNumbers(evt:MouseEvent):void {
    try{
    numberSelect.push(Number(number1.text));
    catch{
    if (numberSelect > 10){
    throw new Error("You must choose a number between 1 - 10");
    button1.addEventListener( MouseEvent.MOUSE_UP, captureNumbers);
    This is what ive got so far which doesn't seem to be working...
    Thanks in advance

    public class userBean(String user) {
         // Loads user preferences
         String fname;
         String lname;
         String greeting;
         void public readDB()
              Connection conn = null;
              PreparedStatement pstmt = null;
              ResultSet result = null;
              try {
                   Class.forName("oracle.jdbc.driver.OracleDriver");
              catch (Exception e) { System.out.println("Can't load JDBC driver:" + e); return; }
                   try{
                   conn = DriverManager.getConnection
                       ("jdbc:oracle:thin:@username.domain.com:1521:adm2", "login", "pass");
                   // @machineName:port:SID,   userid,  password d     
                   stmt = conn.prepareStatement("select fname,lname,greeting from people where userid = ?");
                     stmt.setString(1,user);
                     result= stmt.executeQuery();
                     fname = result.getString(1);
                     lname = result.getString(2);
                     stmt.close();
                   catch (Exception e) { System.out.println("Error with JDBC Connection:" + e); return;}          
    }

  • TRY..catch block in a loop.

    Hi Epxerts,
    Can i use loop endloop for the following TRY..CATCH block as i need to send multiple records
    LOOP.
    TRY.
      Assign row
        it_prxstruc-MT_table_EXTRACT-record-row = wa_area1. --> one record of
        CALL METHOD prxy->execute_asynchronous
          EXPORTING
            output = it_prxstruc --> 1 record.
        COMMIT WORK
      CATCH cx_ai_system_fault .
        DATA fault TYPE REF TO cx_ai_system_fault .
        CREATE OBJECT fault.
        WRITE :/ fault->errortext.
    ENDTRY.
    ENDLOOP.
    Please suggest accordingly.
    Thanks
    Dany

    Try-Endtry specifies the territory of exception that catch is going to handle. Do it this way..
    TRY.
    LOOP.
    Assign row
    it_prxstruc-MT_table_EXTRACT-record-row = wa_area1. --> one record of
    CALL METHOD prxy->execute_asynchronous
    EXPORTING
    output = it_prxstruc --> 1 record.
    COMMIT WORK
    ENDLOOP.
    CATCH cx_ai_system_fault .
    DATA fault TYPE REF TO cx_ai_system_fault .
    CREATE OBJECT fault.
    WRITE :/ fault->errortext.
    ENDTRY.
    G@urav.

  • Is there try and catch in oracle query ?

    hi
    is there try and catch in oracle query ?
    try
    do some update
    catch
    if there was error go to here
    }

    >
    is there try and catch in oracle query ?
    >
    Yes - except it uses BEGIN --- EXCEPTION --- END where BEGIN replaces the try and EXCEPTION replaces the catch.
    BEGIN
    -- Calculation might cause division-by-zero error.
       pe_ratio := stock_price / net_earnings;
       dbms_output.put_line('Price/earnings ratio = ' || pe_ratio);
    EXCEPTION  -- exception handlers begin
    -- Only one of the WHEN blocks is executed.
       WHEN ZERO_DIVIDE THEN  -- handles 'division by zero' error
          dbms_output.put_line('Company must have had zero earnings.');
          pe_ratio := null;
       WHEN OTHERS THEN  -- handles all other errors
          dbms_output.put_line('Some other kind of error occurred.');
          pe_ratio := null;
    END;  -- exception handlers and block end here
    /The multiple WHEN conditions correspond to using multiple 'catch' statements in Java.

  • My Blackberry Curve 8520 screen has gone white but the sounds and everything still work

    My Blackberry Curve 8520 screen has gone white but the sounds and everything still work so i dont know what to do because nothing on youtube tells me what to do so i have ended up here so please can someone help me

    Hello grasyapagsinta
    Welcome to BlackBerry Support Community Forums
    If you think your Battery it OK then try Updating or reloading your device software to rule out any software issue.Have a look at  on how to perform a clean reload of device software :
     KB11320 : How to perform a clean reload of the BlackBerry Device software using BlackBerry desktop software for windows.
    Additional Information :KB30280 : BlackBerry smartphone displays a blank white or black screen.
    Prince
    Click " Like " if you want to Thank someone.
    If Problem Resolves mark the post(s) as " Solution ", so that other can make use of it.
    Click " Like " if you want to Thank someone.
    If Problem Resolves mark the post(s) as " Solution ", so that other can make use of it.

Maybe you are looking for

  • Don't show rows in the dialog once they have been selected

    Hi All, This is more of an approach oriented question rather a technical issue. I am using ADF-BC-JSF Jdeveloper 10.1.3.3. I have 2 master entities and VOs - Employee and ProjectsMaster. Each Employee can work on multiple projects for which I have a

  • Custom infopath task doesn't update in visual studion sequential workflow

    Hi all, I have a probleme with an InfoPath task form I've been looking for a solution to my problem for few days now with now success. I developped a visual studio  sequential workflow, i than designed an infopath Edit Task Form my form have followin

  • /etc/services file deleted?

    I have recently upgraded my Arch box and today I found out that /etc/services was...deleted! The deletion happened on 19 July, this is the relative section of my /var/log/pacman.log: [2010-07-19 14:35] Running '/usr/bin/pacman --noconfirm -Syu' [2010

  • HT2736 Is there a way to put creadit on an iTunes account from an iPhone?

    Is there anyway to add creadit to an iTunes account from an iPhone? I have the iTunes store app

  • Big problem with Mpower z87 + I5 4670K

    Hi My English is not perfect so i'll be quick : Hardware : MSI Mpower Z87 Core i5 4670K 2x4GO DDR3 2400 1.65V EVGA 750W GOLD Water cooling Ati 7950 SSD Samsung 120GO So i'm trying to overclock my 4670K but when my frequency is at 4.2MHZ i am obliged