Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
For 2023 - we are now fully retired from IT training.
We have made many, many friends over 25 years of teaching about Python, Tcl, Perl, PHP, Lua, Java, C and C++ - and MySQL, Linux and Solaris/SunOS too. Our training notes are now very much out of date, but due to upward compatability most of our examples remain operational and even relevant ad you are welcome to make us if them "as seen" and at your own risk.

Lisa and I (Graham) now live in what was our training centre in Melksham - happy to meet with former delegates here - but do check ahead before coming round. We are far from inactive - rather, enjoying the times that we are retired but still healthy enough in mind and body to be active!

I am also active in many other area and still look after a lot of web sites - you can find an index ((here))
Exceptions in Java - why and how

Although it's common practise to include a static main test program in a class, it's something that newcomers can have some difficulty following ... so we don't do it too early on the course - we keep classes and programs that use those classes (even if they are just test programs) each in their own classes and file. But today - the fourth day of Learning to Program in Java, we started to load the test harness into the class. The first example was in the program we called "Wendy" which also showed how base classes inherit from the Universal superclass, and how methods like toString can be overridden to allow objects to be easily printed.

Here are the four (quite major!) extra examples I wrote today:

Wendy.java   Test program within a class
Xena.java   Example with and without exception handling
Yvonne.java   Directory listing, file i/o and formatting demo
Zoe.java   StringTokeniszer, ArrayList and Exception demonstration

Exceptions are a vital part of Java, and although we have a complete module on them in our training notes, I see I've only ever skirted around the subject on my Blog .... so here's a bit more.

Principle of exceptions

When you run a piece of code, it may or may not do what you want / come up with the sort of result you were looking for. In many older languages, you had to check a return status from each function call to see if it really had worked, or look for some 'cardinal' or special value that was returned - which made for messy code - not quite spaghetti, but certainly Pasta ;-).

Exceptions take out the need for checking every single action for a status - you can group together a whole series of operations and say "Try this" ... with the code jumping to a block that processes any error - a "catch" block - which mops up any problems.

You can also throw exceptions yourself - if you're writing a function that analyses an Apache log file line and creates an object from it BUT the line of data isn't actually a valid log file line, for example, you can throw an exception. And if you're running a function who's role it is to return the number of children that Jerry has, but you don't know, you can raise and throw an exception rather than passing back an impossible integer value that the calling program has to check for.

Excpetions can be handled by the function in which they occur, or can be passed back to the calling code. This is rather like having a child that's got a problem (needs the loo). You can either let the child sort the problem out itself, or have it pull on the coattails of the calling function - "Mum - I need to GO!!!". Of course, if Mum is busy she can then pass on the problem to Granny ...

Exceptions in Java

Here's a simple piece of code that takes 4 command line arguments - two names and two ages - and tells people how much longer they must work:

for (int k=0; k<4; k+=2) {
int retire = 65 - Integer.parseInt(args[k+1]);
System.out.println(args[k] + " can retire in "
+retire+" years"); }

It works well enough if you put sensible values in:

Dorothy-2:java grahamellis$ java Xena Bob 23 Roberta 26
Bob can retire in 42 years
Roberta can retire in 39 years
Dorothy-2:java grahamellis$

but put in too few values, or fail to have numbers as the 2nd or 4th parameters, and it generates some serious errors. Here's the same code, rewritten to catch the possible exceptions and act on what it has caught:

for (int k=0; k<4; k+=2) {
 retire = 999;
 try {
   retire = 65 - Integer.parseInt(args[k+1]);
 } catch (ArrayIndexOutOfBoundsException e) {
   System.out.println("I've run out of data");
 } catch (NumberFormatException anything) {
   System.out.println("Wanted no.; got str\n" +
   retire = 50; // Assume whole working life!
 } catch (Exception e) {
   System.out.println("Summat else failed");
 System.out.println(args[k] +
    " can retire in "+retire+" years");

You'll note that we have chosen to catch some specific types of exception first, but then the more general "Exception" as a safety net. If we run out of arguments on the command line, we break out of the for loop as there's no point in going on to generate more error messages, but if we simply have a problem getting a number out of a field, we do carry on to trying out later fields. It's amazing just how much care is needed even in exception handling - the blocking is every bit as important as the block structure of while and if.

The full source of the example above, together with some output samples in both its original (unchecked) and properly checked forms, is here.
(written 2009-09-24, updated 2009-09-25)

Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
J713 - Java - More Input and Output
  [1239] End of File on a Java BufferedReader - (2007-06-22)
  [4350] Keyboard reader for Java programming newcomers - (2014-12-12)
  [4414] Java - converting an integer to a fixed length string - (2015-02-04)
  [4420] Flexibility in input - read from file, web resource or keyboard - (2015-02-08)

J712 - Java - Exceptions
  [1066] Final, Finally and Finalize - three special words in Java - (2007-02-05)
  [1875] What are exceptions - Python based answer - (2008-11-08)
  [2622] Handling unusual and error conditions - exceptions - (2010-02-03)
  [2862] Fail Safe Error Handling in Java via Exceptions - (2010-07-09)
  [3045] After Course Resources - do we publish sample answers. Example from Java Exceptions module. - (2010-11-13)
  [3048] String handling - from first steps to practical examples - (2010-11-13)
  [4396] Java Utility class - flexible replacement for array. Also cacheing in objects and multiple catch clauses example. - (2015-01-16)

J050 - Java - General
  [2087] Comparing Java Courses - what can we do? - (2009-03-17)
  [2091] C, C++ and C# ... Java and JavaScript - (2009-03-20)
  [2114] Which Version of Java am I running? - (2009-04-02)
  [2417] Java Programming Fundamentals - (2009-09-24)
  [2504] Learning to program in ... - (2009-11-15)
  [2861] MySQL and Java - connectivity past, present, and future thoughts - (2010-07-09)
  [3573] New in Java 7 - and why we are not running public Java 7 courses - (2012-01-08)
  [4305] Learning to program in Java - yes, we can help. - (2014-09-26)
  [4317] Java - an update of the basics - (2014-11-16)
  [4412] Java -making sure you have the right versions - (2015-02-02)
  [4430] The spirit of Java - delegating to classes - (2015-02-18)

Back to
Where is my Java class?
Previous and next
Horse's mouth home
Forward to
Sorting Collections of Objects in Java
Some other Articles
A Winter Weekend Special at Well House Manor
What is a JVM, a JRE, a JDK - components of the core Java Environment
Looking inside Java classes - javap and javadoc
Sorting Collections of Objects in Java
Exceptions in Java - why and how
Where is my Java class?
Viv.java uses unchecked or unsafe operations - explanation and cure
Automating access to a page obscured behind a holding page
Variable names like i and j - why?
4759 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96 at 50 posts per page

This is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price.

Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2023: 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/mouth/2420_Exc ... d-how.html • PAGE BUILT: Sun Oct 11 16:07:41 2020 • BUILD SYSTEM: JelliaJamb