Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Java exception handling performance tips
New Posts  All Forums:Forum Nav:

Java exception handling performance tips

post #1 of 6
Thread Starter 
In the example below, the scanner is closed in the try block vs the finally block because...if an exception occurs (and the scanner is closed in the finally block), the scanner will be closed before control resumes at the try block which will result in an error.

From a performance perspective, would it be better to leave the code as is, or create the scanner in the try block? Basically...create the scanner once or potentially many times?

I realize that it probably doesn't matter in the example below, but for future reference would it matter for things like database connections? Thanks in advance.
Code:
import java.util.InputMismatchException;
import java.util.Scanner;

public class DivideByZero 
{
     public static int quotient(int numerator, int denominator)
               throws ArithmeticException
     {
               return numerator / denominator;
     }

     public static void main(String[] args)
     {
               Scanner scanner = new Scanner(System.in);

               boolean continueLoop = true;

     do
     {
               try
               {
                         System.out.print("input an integer numerator ");
                         int numerator = scanner.nextInt();

                         System.out.print("input an integer denominator ");
                         int denominator = scanner.nextInt();
                              
                         int result = quotient(numerator, denominator);

                         System.out.printf("%d / %d = %d", numerator, denominator, result);

                         continueLoop = false;

                         scanner.close();
               }

               catch (InputMismatchException e)
               {
                         System.out.println("\ninvalid input; integers only. please try again.\n");
                         scanner.nextLine();
               }

               catch (ArithmeticException e)
               {
                         System.out.println("\nzero is an invalid denominator. please try again.\n");
               }

               finally
               {
                        //scanner.close();
               }

               } while ( continueLoop );

     } // end method main

}

Edited by semnon - 9/29/13 at 9:44pm
Realm
(14 items)
 
  
CPUMotherboardRAMHard Drive
i7-4770K ASUS Maximus VI Extreme Patriot Viper Xtreme Intel 730 SSD 
Hard DriveCoolingOSMonitor
Western Digital VelociRaptor Corsair H100i Win 8.1 Acer X223W 
KeyboardPowerCaseMouse
HHKB Professional 2 Corsair AX1200i Danger Den Q20 Razer Mamba 
Mouse Pad
Razer Manticore 
  hide details  
Reply
Realm
(14 items)
 
  
CPUMotherboardRAMHard Drive
i7-4770K ASUS Maximus VI Extreme Patriot Viper Xtreme Intel 730 SSD 
Hard DriveCoolingOSMonitor
Western Digital VelociRaptor Corsair H100i Win 8.1 Acer X223W 
KeyboardPowerCaseMouse
HHKB Professional 2 Corsair AX1200i Danger Den Q20 Razer Mamba 
Mouse Pad
Razer Manticore 
  hide details  
Reply
post #2 of 6

Wrap try ... finally around the loop instead of inside it - solves both problems. Close the scanner inside finally. Currently, if an exception occurs the scanner will leak.

Ol' Sandy
(28 items)
 
"Zeus"
(12 items)
 
Elite Preview
(6 items)
 
CPUMotherboardGraphicsRAM
Intel Xeon E3-1230v3 Gigabyte GA-Z97X-UD5H-BK MSI Gaming GTX 980 Kingston 32GB (4x8) 
Hard DriveHard DriveHard DriveHard Drive
Plextor PX-256M5S 256GB Samsung EVO 1TB Hitachi HDS721010CLA332 Hitachi HDS723020BLA642 
Hard DriveHard DriveHard DriveOptical Drive
Hitachi HDS723020BLA642 Hitachi HUA722010CLA330 WDC WD10EARS-00Z5B1 TSSTcorp CDDVDW SH-S223B 
CoolingCoolingOSMonitor
Phanteks PH-TC14PE with TY-140's Lamptron FCv5 (x2) Windows 8 Pro 64-bit Dell U2412M 
MonitorMonitorMonitorKeyboard
Dell U2412M Dell U2212HM Dell U2713HM Topre Realforce 87UB | Ducky DK9087 G2 Pro 
PowerCaseMouseMouse Pad
Corsair AX-750 Corsair Obsidian 650D Logitech G700 XTRAC Ripper XXL 
AudioAudioAudioAudio
Beyerdynamic DT-770 Pro 250ohm Schiit Bifrost DAC Schiit Asgard 2 HiVi Swan M50W 2.1 
CPUMotherboardRAMHard Drive
Intel Xeon E5-2620 Super Micro X9SRL-F-B 128GB 1333MHz LSI 9271-8i 
OSPowerCase
VMware ESXi 5.5 SeaSonic SS-400FL2 Fractal Define R3 
CPUMotherboardGraphicsRAM
Intel Core i5-3437U HP EliteBook Folio 9470m  Intel HD Graphics 4000  16GB DDR3 SDRAM 
Hard DriveOS
256GB SSD Windows 10 Insider Preview 
  hide details  
Reply
Ol' Sandy
(28 items)
 
"Zeus"
(12 items)
 
Elite Preview
(6 items)
 
CPUMotherboardGraphicsRAM
Intel Xeon E3-1230v3 Gigabyte GA-Z97X-UD5H-BK MSI Gaming GTX 980 Kingston 32GB (4x8) 
Hard DriveHard DriveHard DriveHard Drive
Plextor PX-256M5S 256GB Samsung EVO 1TB Hitachi HDS721010CLA332 Hitachi HDS723020BLA642 
Hard DriveHard DriveHard DriveOptical Drive
Hitachi HDS723020BLA642 Hitachi HUA722010CLA330 WDC WD10EARS-00Z5B1 TSSTcorp CDDVDW SH-S223B 
CoolingCoolingOSMonitor
Phanteks PH-TC14PE with TY-140's Lamptron FCv5 (x2) Windows 8 Pro 64-bit Dell U2412M 
MonitorMonitorMonitorKeyboard
Dell U2412M Dell U2212HM Dell U2713HM Topre Realforce 87UB | Ducky DK9087 G2 Pro 
PowerCaseMouseMouse Pad
Corsair AX-750 Corsair Obsidian 650D Logitech G700 XTRAC Ripper XXL 
AudioAudioAudioAudio
Beyerdynamic DT-770 Pro 250ohm Schiit Bifrost DAC Schiit Asgard 2 HiVi Swan M50W 2.1 
CPUMotherboardRAMHard Drive
Intel Xeon E5-2620 Super Micro X9SRL-F-B 128GB 1333MHz LSI 9271-8i 
OSPowerCase
VMware ESXi 5.5 SeaSonic SS-400FL2 Fractal Define R3 
CPUMotherboardGraphicsRAM
Intel Core i5-3437U HP EliteBook Folio 9470m  Intel HD Graphics 4000  16GB DDR3 SDRAM 
Hard DriveOS
256GB SSD Windows 10 Insider Preview 
  hide details  
Reply
post #3 of 6
Thread Starter 
tompsonn,

Below are my changes. Whenever an exception occurs, the program stops because there is no looping. Did I forget to add something?
Code:
import java.util.Scanner;

   public class Test 
   {
      public static void main(String[] args)
      {
      Scanner scanner = new Scanner(System.in);

      boolean continueLoop = true;

      try
      {
          do
          {
              System.out.print("enter an integer: ");
              int number = scanner.nextInt();

              continueLoop = false;
          }
          while (continueLoop);
       }
      catch (Exception e)
      {
          System.out.println("error");
      }
      finally
      {
         scanner.close();
      }
   }

}

Edited by semnon - 9/30/13 at 8:21pm
Realm
(14 items)
 
  
CPUMotherboardRAMHard Drive
i7-4770K ASUS Maximus VI Extreme Patriot Viper Xtreme Intel 730 SSD 
Hard DriveCoolingOSMonitor
Western Digital VelociRaptor Corsair H100i Win 8.1 Acer X223W 
KeyboardPowerCaseMouse
HHKB Professional 2 Corsair AX1200i Danger Den Q20 Razer Mamba 
Mouse Pad
Razer Manticore 
  hide details  
Reply
Realm
(14 items)
 
  
CPUMotherboardRAMHard Drive
i7-4770K ASUS Maximus VI Extreme Patriot Viper Xtreme Intel 730 SSD 
Hard DriveCoolingOSMonitor
Western Digital VelociRaptor Corsair H100i Win 8.1 Acer X223W 
KeyboardPowerCaseMouse
HHKB Professional 2 Corsair AX1200i Danger Den Q20 Razer Mamba 
Mouse Pad
Razer Manticore 
  hide details  
Reply
post #4 of 6
Quote:
Originally Posted by semnon View Post

tompsonn,

Below are my changes. Whenever an exception occurs, the program stops because there is no looping. Did I forget to add something?
Code:
import java.util.Scanner;

   public class Test 
   {
      public static void main(String[] args)
      {
      Scanner scanner = new Scanner(System.in);

      boolean continueLoop = true;

      try
      {
          do
          {
              System.out.print("enter an integer: ");
              int number = scanner.nextInt();

              continueLoop = false;
          }
          while (continueLoop);
       }
      catch (Exception e)
      {
          System.out.println("error");
      }
      finally
      {
         scanner.close();
      }
   }

}

Well to be perfectly honest, the exception shouldn't occur - but its fine to handle ones that are caused by bad user input. Its also bad practice to do a catch all where you catch Exception (which catches all types of exceptions). If all you want to do is make sure the scanner is closed properly (and I would suggest its better to only create one scanner like you're doing, you can use multiple try ... catch blocks):

 



import java.util.Scanner;

public class Test
{
    
    public static void main(String[] args)
    {
        
        Scanner scanner = new Scanner(System.in);
        
        boolean continueLoop = true;
        
        try
        {
            
            try
            {
                
                do
                {
                    
                    System.out.print("enter an integer: ");
                    int number = scanner.nextInt();
                    
                    continueLoop = false;
                    
                }
                
                while (continueLoop);
                
            }
            
            catch (InputMismatchException e)
            {
                
                System.out.println("\ninvalid input; integers only. please try again.\n");
                scanner.nextLine();
                
            }
            
            
            catch (ArithmeticException e)
            {
                
                System.out.println("\nzero is an invalid denominator. please try again.\n");
                
            }
            
            
        }
        
        finally
        {
            
            scanner.close();
            
        }
        
        
    }
    
    
    
}


Ol' Sandy
(28 items)
 
"Zeus"
(12 items)
 
Elite Preview
(6 items)
 
CPUMotherboardGraphicsRAM
Intel Xeon E3-1230v3 Gigabyte GA-Z97X-UD5H-BK MSI Gaming GTX 980 Kingston 32GB (4x8) 
Hard DriveHard DriveHard DriveHard Drive
Plextor PX-256M5S 256GB Samsung EVO 1TB Hitachi HDS721010CLA332 Hitachi HDS723020BLA642 
Hard DriveHard DriveHard DriveOptical Drive
Hitachi HDS723020BLA642 Hitachi HUA722010CLA330 WDC WD10EARS-00Z5B1 TSSTcorp CDDVDW SH-S223B 
CoolingCoolingOSMonitor
Phanteks PH-TC14PE with TY-140's Lamptron FCv5 (x2) Windows 8 Pro 64-bit Dell U2412M 
MonitorMonitorMonitorKeyboard
Dell U2412M Dell U2212HM Dell U2713HM Topre Realforce 87UB | Ducky DK9087 G2 Pro 
PowerCaseMouseMouse Pad
Corsair AX-750 Corsair Obsidian 650D Logitech G700 XTRAC Ripper XXL 
AudioAudioAudioAudio
Beyerdynamic DT-770 Pro 250ohm Schiit Bifrost DAC Schiit Asgard 2 HiVi Swan M50W 2.1 
CPUMotherboardRAMHard Drive
Intel Xeon E5-2620 Super Micro X9SRL-F-B 128GB 1333MHz LSI 9271-8i 
OSPowerCase
VMware ESXi 5.5 SeaSonic SS-400FL2 Fractal Define R3 
CPUMotherboardGraphicsRAM
Intel Core i5-3437U HP EliteBook Folio 9470m  Intel HD Graphics 4000  16GB DDR3 SDRAM 
Hard DriveOS
256GB SSD Windows 10 Insider Preview 
  hide details  
Reply
Ol' Sandy
(28 items)
 
"Zeus"
(12 items)
 
Elite Preview
(6 items)
 
CPUMotherboardGraphicsRAM
Intel Xeon E3-1230v3 Gigabyte GA-Z97X-UD5H-BK MSI Gaming GTX 980 Kingston 32GB (4x8) 
Hard DriveHard DriveHard DriveHard Drive
Plextor PX-256M5S 256GB Samsung EVO 1TB Hitachi HDS721010CLA332 Hitachi HDS723020BLA642 
Hard DriveHard DriveHard DriveOptical Drive
Hitachi HDS723020BLA642 Hitachi HUA722010CLA330 WDC WD10EARS-00Z5B1 TSSTcorp CDDVDW SH-S223B 
CoolingCoolingOSMonitor
Phanteks PH-TC14PE with TY-140's Lamptron FCv5 (x2) Windows 8 Pro 64-bit Dell U2412M 
MonitorMonitorMonitorKeyboard
Dell U2412M Dell U2212HM Dell U2713HM Topre Realforce 87UB | Ducky DK9087 G2 Pro 
PowerCaseMouseMouse Pad
Corsair AX-750 Corsair Obsidian 650D Logitech G700 XTRAC Ripper XXL 
AudioAudioAudioAudio
Beyerdynamic DT-770 Pro 250ohm Schiit Bifrost DAC Schiit Asgard 2 HiVi Swan M50W 2.1 
CPUMotherboardRAMHard Drive
Intel Xeon E5-2620 Super Micro X9SRL-F-B 128GB 1333MHz LSI 9271-8i 
OSPowerCase
VMware ESXi 5.5 SeaSonic SS-400FL2 Fractal Define R3 
CPUMotherboardGraphicsRAM
Intel Core i5-3437U HP EliteBook Folio 9470m  Intel HD Graphics 4000  16GB DDR3 SDRAM 
Hard DriveOS
256GB SSD Windows 10 Insider Preview 
  hide details  
Reply
post #5 of 6
Thread Starter 
OK. I got it working.
Code:
import java.util.Scanner;

public class Test 
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);

boolean continueLoop = true;

try
{

do
{
try
{
System.out.print("enter an integer: ");
int number = scanner.nextInt();

System.out.println("your interger is " + number);
continueLoop = false;
}
catch (Exception e)
{
System.out.println("error");
scanner.nextLine();
}
}
while (continueLoop);
}
finally
{
System.out.println("scanner is closing");
scanner.close();
}
}
}

Thanks for your help. Do you know why my code is left justified every time I hit submit? When I paste it, it's indented.
Realm
(14 items)
 
  
CPUMotherboardRAMHard Drive
i7-4770K ASUS Maximus VI Extreme Patriot Viper Xtreme Intel 730 SSD 
Hard DriveCoolingOSMonitor
Western Digital VelociRaptor Corsair H100i Win 8.1 Acer X223W 
KeyboardPowerCaseMouse
HHKB Professional 2 Corsair AX1200i Danger Den Q20 Razer Mamba 
Mouse Pad
Razer Manticore 
  hide details  
Reply
Realm
(14 items)
 
  
CPUMotherboardRAMHard Drive
i7-4770K ASUS Maximus VI Extreme Patriot Viper Xtreme Intel 730 SSD 
Hard DriveCoolingOSMonitor
Western Digital VelociRaptor Corsair H100i Win 8.1 Acer X223W 
KeyboardPowerCaseMouse
HHKB Professional 2 Corsair AX1200i Danger Den Q20 Razer Mamba 
Mouse Pad
Razer Manticore 
  hide details  
Reply
post #6 of 6
Quote:
Originally Posted by semnon View Post

OK. I got it working.
Thanks for your help. Do you know why my code is left justified every time I hit submit? When I paste it, it's indented.

Welcome smile.gif

Yes I do - this forum platform is a joke. santa.gif
Ol' Sandy
(28 items)
 
"Zeus"
(12 items)
 
Elite Preview
(6 items)
 
CPUMotherboardGraphicsRAM
Intel Xeon E3-1230v3 Gigabyte GA-Z97X-UD5H-BK MSI Gaming GTX 980 Kingston 32GB (4x8) 
Hard DriveHard DriveHard DriveHard Drive
Plextor PX-256M5S 256GB Samsung EVO 1TB Hitachi HDS721010CLA332 Hitachi HDS723020BLA642 
Hard DriveHard DriveHard DriveOptical Drive
Hitachi HDS723020BLA642 Hitachi HUA722010CLA330 WDC WD10EARS-00Z5B1 TSSTcorp CDDVDW SH-S223B 
CoolingCoolingOSMonitor
Phanteks PH-TC14PE with TY-140's Lamptron FCv5 (x2) Windows 8 Pro 64-bit Dell U2412M 
MonitorMonitorMonitorKeyboard
Dell U2412M Dell U2212HM Dell U2713HM Topre Realforce 87UB | Ducky DK9087 G2 Pro 
PowerCaseMouseMouse Pad
Corsair AX-750 Corsair Obsidian 650D Logitech G700 XTRAC Ripper XXL 
AudioAudioAudioAudio
Beyerdynamic DT-770 Pro 250ohm Schiit Bifrost DAC Schiit Asgard 2 HiVi Swan M50W 2.1 
CPUMotherboardRAMHard Drive
Intel Xeon E5-2620 Super Micro X9SRL-F-B 128GB 1333MHz LSI 9271-8i 
OSPowerCase
VMware ESXi 5.5 SeaSonic SS-400FL2 Fractal Define R3 
CPUMotherboardGraphicsRAM
Intel Core i5-3437U HP EliteBook Folio 9470m  Intel HD Graphics 4000  16GB DDR3 SDRAM 
Hard DriveOS
256GB SSD Windows 10 Insider Preview 
  hide details  
Reply
Ol' Sandy
(28 items)
 
"Zeus"
(12 items)
 
Elite Preview
(6 items)
 
CPUMotherboardGraphicsRAM
Intel Xeon E3-1230v3 Gigabyte GA-Z97X-UD5H-BK MSI Gaming GTX 980 Kingston 32GB (4x8) 
Hard DriveHard DriveHard DriveHard Drive
Plextor PX-256M5S 256GB Samsung EVO 1TB Hitachi HDS721010CLA332 Hitachi HDS723020BLA642 
Hard DriveHard DriveHard DriveOptical Drive
Hitachi HDS723020BLA642 Hitachi HUA722010CLA330 WDC WD10EARS-00Z5B1 TSSTcorp CDDVDW SH-S223B 
CoolingCoolingOSMonitor
Phanteks PH-TC14PE with TY-140's Lamptron FCv5 (x2) Windows 8 Pro 64-bit Dell U2412M 
MonitorMonitorMonitorKeyboard
Dell U2412M Dell U2212HM Dell U2713HM Topre Realforce 87UB | Ducky DK9087 G2 Pro 
PowerCaseMouseMouse Pad
Corsair AX-750 Corsair Obsidian 650D Logitech G700 XTRAC Ripper XXL 
AudioAudioAudioAudio
Beyerdynamic DT-770 Pro 250ohm Schiit Bifrost DAC Schiit Asgard 2 HiVi Swan M50W 2.1 
CPUMotherboardRAMHard Drive
Intel Xeon E5-2620 Super Micro X9SRL-F-B 128GB 1333MHz LSI 9271-8i 
OSPowerCase
VMware ESXi 5.5 SeaSonic SS-400FL2 Fractal Define R3 
CPUMotherboardGraphicsRAM
Intel Core i5-3437U HP EliteBook Folio 9470m  Intel HD Graphics 4000  16GB DDR3 SDRAM 
Hard DriveOS
256GB SSD Windows 10 Insider Preview 
  hide details  
Reply
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Coding and Programming
Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Java exception handling performance tips