Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
For 2021 - online Python 3 training - see ((here)).

Our plans were to retire in summer 2020 and see the world, but Coronavirus has lead us into a lot of lockdown programming in Python 3 and PHP 7.
We can now offer tailored online training - small groups, real tutors - works really well for groups of 4 to 14 delegates. Anywhere in the world; course language English.

Please ask about private 'maintenance' training for Python 2, Tcl, Perl, PHP, Lua, etc.
Practical Exception Handling Example
Exceptions example from a Well House Consultants training course
More on Exceptions [link]

This example is described in the following article(s):
   • String handling - from first steps to practical examples - [link]

Source code: Bikini.java Module: J712
import java.io.*;
import java.util.*;

/* Practical Exception Handling Example

This is an example that opens and reads from a data file, storing information into
an ArrayList and a HashMap as it stored the information it needs for a report.

Exceptions used within the main code to trap program runs where no input file is
specified, or the input file named doesn't exist or can't be read. And we've also
used our own exception if our call to "getCountry" isn't going to be able to identify
tehe origin of the request. */

public class Bikini {

        public static String getCountry(String Ip) {

                // Throws an exception if cannot resolve to a country
                // (IRL - use this to call www.maxmind.com's database!)

                // Failure - throw an exception rather than returning a value

                if (! Ip.startsWith("66")) {
                        ArrayIndexOutOfBoundsException fred = new
                                ArrayIndexOutOfBoundsException("Dunno, Mate!");
                        throw fred;

                // Success - return a value

                return "Potential Googleland";

        public static void main (String [] args) {

                int countplace = 0, countlines = 0;
                int iptop; String RemoteIp;

                BufferedReader Suck = null;

// Open the input file - deal with any issues if you can't

                try {
                        Suck = new BufferedReader(new FileReader(args[0]));
                catch (ArrayIndexOutOfBoundsException e) {
                        // Failed to specify file name
                        System.err.println ("Hey - where should I look?");
                catch (Exception e) {
                        // Name given doesn't map to a file that can be read
                        System.err.println ("Oh Sh..dear");
                        System.err.println ("Contact the support team: " + e);

                String Stuff;

                // Read and store all Swindon interest by IP

                ArrayList<String> Iprecords = new ArrayList<String>();

                // Also store a count of visits from each different IP

                HashMap Counters = new HashMap();

                try { // In case data stream breaks
                while ((Stuff = Suck.readLine()) != null) {
                        countlines ++;
                        iptop = Stuff.indexOf(" ");
                        RemoteIp = Stuff.substring(0,iptop);
                        if (Stuff.indexOf("Swindon") >= 0) {

                                        // Store onto an ArrayList


                                        // Also store into a HashMap

                                        // Get count so far for this IP from Hashmap
                                        Integer temp = (Integer)Counters.get(RemoteIp);
                                        // If this is an IP we have not seen before, set 0
                                        if (temp == null) temp = new Integer(0);
                                        // Store one more than previous value into Hashmap
                                        Integer newval = new Integer(1+temp.intValue());



                } catch (IOException e) {
                        System.err.println("Problem reading file");

                System.out.println("Total " + countlines);
                System.out.println("Matched " + countplace);

                // And print out IP list too

                for (int k=0; k<Iprecords.size(); k++) {
                        String iprecalled = Iprecords.get(k);


                // Print out IP list with times each occurred from the HashMap

                // Get the keys so that we can handle them each in turn [keyset]
                Set HostKeys = Counters.keySet();
                // Make an iterator which can step through the keyset one by one
                Iterator It = HostKeys.iterator();

                // "while we still have data available from the iterator ..."
                while (It.hasNext()) {
                        // " ... get the next piece of data [key]"
                        String HostNow = (String)(It.next());
                        int c = ((Integer)Counters.get(HostNow)).intValue();

                        String Country = null;
                        try {
                                Country = getCountry(HostNow);
                        } catch (Exception e) {
                                Country = "Dunno where!";

                        // Print out the IP addresses and the counts alongside
                        System.out.println((String)HostNow + " - " + c +
                                        " - " + Country);

/* Sample Outputs ...

wizard:jn10 graham$ java Bikini
Hey - where should I look?
wizard:jn10 graham$ java Bikini ac_20101100
Oh Sh..dear
Contact the support team: java.io.FileNotFoundException: ac_20101100 (No such file or directory)
wizard:jn10 graham$ java Bikini ac_20101102
Total 170046
Matched 48
---------------- - 2 - Potential Googleland - 4 - Dunno where! - 3 - Dunno where! - 2 - Potential Googleland - 1 - Dunno where! - 2 - Potential Googleland - 1 - Potential Googleland - 1 - Dunno where! - 1 - Potential Googleland - 1 - Dunno where! - 4 - Potential Googleland - 3 - Dunno where! - 1 - Dunno where! - 1 - Dunno where! - 5 - Dunno where! - 3 - Dunno where! - 10 - Dunno where! - 1 - Potential Googleland - 1 - Dunno where! - 1 - Potential Googleland
wizard:jn10 graham$


Learn about this subject
This module and example are covered on the following public courses:
 * Learning to Program in Java
 * Java Bootcamp
 * Java Programming for the Web
Also available on on site courses for larger groups

Books covering this topic
Yes. We have over 700 books in our library. Books covering Java and associated technologies are listed here and when you've selected a relevant book we'll link you on to Amazon to order.

Other Examples
This example comes from our "Exceptions" training module. You'll find a description of the topic and some other closely related examples on the "Exceptions" module index page.

Full description of the source code
You can learn more about this example on the training courses listed on this page, on which you'll be given a full set of training notes.

Many other training modules are available for download (for limited use) from our download centre under an Open Training Notes License.

Other resources
• Our Solutions centre provides a number of longer technical articles.
• Our Opentalk forum archive provides a question and answer centre.
The Horse's mouth provides a daily tip or thought.
• Further resources are available via the resources centre.
• All of these resources can be searched through through our search engine
• And there's a global index here.

Web site author
This web site is written and maintained by Well House Consultants.

Purpose of this website
This is a sample program, class demonstration or answer from a training course. It's main purpose is to provide an after-course service to customers who have attended our public private or on site courses, but the examples are made generally available under conditions described below.

Conditions of use
Past attendees on our training courses are welcome to use individual examples in the course of their programming, but must check the examples they use to ensure that they are suitable for their job. Remember that some of our examples show you how not to do things - check in your notes. Well House Consultants take no responsibility for the suitability of these example programs to customer's needs.

This program is copyright Well House Consultants Ltd. You are forbidden from using it for running your own training courses without our prior written permission. See our page on courseware provision for more details.

Any of our images within this code may NOT be reused on a public URL without our prior permission. For Bona Fide personal use, we will often grant you permission provided that you provide a link back. Commercial use on a website will incur a license fee for each image used - details on request.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2022: 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/resources/ex.php • PAGE BUILT: Sun Oct 11 14:50:09 2020 • BUILD SYSTEM: JelliaJamb