Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exception Handling, Packages

Similar presentations


Presentation on theme: "Exception Handling, Packages"— Presentation transcript:

1 Exception Handling, Packages
Basic Level day 2 Part A Exception Handling, Packages Athanasios Tsintsifas, LTR, University of Nottingham, http:

2 Aims Understand Java’s Exception Mechanism. Learn about Errors.
Be able to catch and throw Exceptions. Understand packages and their use. Learn about accessibility modifiers.

3 Exceptions There is a trade-off between correctness and clarity :
Correctness, checking for errors. Clarity, a clear and readable basic flow of the code. Exceptions are a clean way to manage abnormal states. Exception : mild error which you can handle. Error : serious error -> termination. The idea is to signal exceptions to the current running process announcing that a problem has occurred. An exception is thrown and then caught.

4 Exceptions An exception arises in code at runtime.
Exceptions can appear asynchronously in a method. Two subclasses extending Throwable : Exception, Error. Un-handled exceptions -> Error (Catastrophic failure). RuntimeException.

5 try - catch - finally Statement
// block of code that may throw an exception. [ return; ] } catch (ExceptionType1 e) { // Exception handler for type1 catch (ExceptionType2 e) { // Exception handler for type2 throw(e) // re-throw e Exception finally { // clean-up code try catch finally

6 Exception Handling Example
public class ExceptionExample { public static void main (String[] argv) { int [] numArray; // declaration numArray = new int[10]; // creation try { for (int x=0; x<numArray.length +1; x++) { numArray[x] = x * 2; System.out.print(numArray[x] + ":"); } catch (ArrayIndexOutOfBoundsException ex) { System.out.println("Array Exception caught!!"); finally { System.out.println("Reached finally clause"); Causes the Exception

7 RuntimeExceptions ArithmeticException : int i = 14/0;
ArrayIndexOutOfBoundsException : int[] p = new int[5]; p[6]=10; ClassNotFoundException IllegalArgumentException InstantiationException NegativeArraySizeException NoSuchMethodException : (new Circle()).getEdges(); NullPointerException : Circle cl; cl.getSurface(); StringIndexOutOfBoundsException

8 Errors ? IllegalAccessError IncompatibleClassChangeError
InstantiationError InternalError LinkageError NoClassDefFoundError NoSuchMethodError OutOfMemoryError StackOverflowError ClassCircularityError ClassFormatError

9 Creating Exception Types
public class myException extends Exception { public String message; public myException(String msg) { message = msg; }

10 "throw" an Exception public void test( ) throws myException {
Shape sh = getShape(); if (sh == null) throw new myException(“No Shape was found”); sh.draw(); }

11 Java’s Packages Package is a:
a Path to a directory containing a set of classes, a name space, and a naming mechanism.

12 Java’s Source Files Java files consists of :
1. A single package statement (optional). 2. Any number of import statements (optional). 3. Any number of package private classes (optional). 4. A single public class declaration with the same name as the file.

13 Accessing classes in other packages
There are three ways to access classes in other packages : 1. Write the full name of the class. class ExitFrame extends java.awt.Frame { ... } 2. Import a specific class import java.awt.Frame; class ExitFrame extends Frame { ... } 3. Import all exported classes from a package import java.awt.*;

14 Packages and the CLASSPATH
CLASSPATH is a environmental variable that holds directory paths to java classes. To execute a class file that belongs to a package, a. Put the class file in a appropriate directory. i.e. if package cm.cmd.tool; then ../cm/cmd/tool/ b. make sure that CLASSPATH knows the path to the classes in need. CLASSPATH

15 Name spaces Package names, Class names, Method names, Variable names,
Label names. class Reuse { Reuse Reuse(Reuse Reuse) { Reuse: for(;;) { if (Reuse.Reuse(Reuse) == Reuse) break Reuse; } return Reuse;

16 Modifiers for Class Name-space
Qualifier Scope < none > package public all

17 Modifiers for Methods and Field name-space
Qualifier Scope private class < none > class + package protected class + subclass + package public global

18 Final Modifier Can never be sub-classed by any other class.
final class : Can never be sub-classed by any other class. final method : A subclass can not override a final method. final field : Variables that can never change, constants! Two reasons for making methods final : Security : No one can change the behavior of a method (or class). Performance : Inlining.

19 Design Classes for Extension
Every class has two contracts : Usage contract : Public fields and methods. Extension contract : Protected fields and methods. If a method should be final is a matter of trust. All fields that a final method uses should be made private.

20 Summary Java’s Exception handling mechanism provides a means to deal efficiently with Errors and Exceptions. Exceptions can be caught and thrown. Runtime Exceptions provide a safety layer. Errors usually cause program’s termination. Packages are a means of clustering related classes. Access Modifiers for Class, Fields, and methods : private, public, protected, final, static. Usage Contract - Extension Contract.

21 Quiz How could you make sure that the following lines of code will never cause the program to terminate? Point p = getPoint(); x = p.getX(); y = p.getY(); Assume you have a class called myClass inside package aaa.bbb Where do you need to put the myClass.class file ? Where does the CLASSPATH needs to point to execute the myClass.class ? Is there any meaning for a final abstract method?

22 Exercises Write a program to simulate the conditions under which the following exceptions are thrown : NullPointerException, NegativeArraySizeException, ArrayIndexOutOfBoundsException. Use the try and cartch statements to recover. Write a very simple method to validate a password. In case the password is wrong, throw an InvalidPassword exception to signal the errror to the caller. Try to put any of the programs that you have written until now into a package and execute it.

23 Basic Level day 2 Part B Java’s main packages
Athanasios Tsintsifas, LTR, University of Nottingham, http:

24 Aims Go through JDK1.1’s packages.
Get an idea of the important classes residing inside Java’s 5 main packages : java.lang, java.util, java.io, java.net, java.awt Understand more about how to use classes and their methods. Read and write Java source code easier.

25 Using Java’s Packages Packages group classes with relating functionality. Two ways to (re)use an existing class : Composition, Subclassing. To use a class you need to read its interface.

26 Java’s Packages Java 1.02 Java 1.1 Java 1.2 java.beans java.math
java.rmi java.security java.sql java.text java.util.zip java.lang java.io java.util java.net java.awt java.applet java.awt.swing.* java.awt.* java.util.* org.omg.CORBA.*

27 java.lang

28 Example 1: Time Counter for a key press
import java.io.*; public class CountTime { public static void main(String args[]) { long startTime, endTime, userTime; DataInputStream dis; String inputString; System.out.print("Press return..."); startTime = System.currentTimeMillis(); dis = new DataInputStream(System.in); try{ inputString = dis.readLine(); } catch (Exception e) { System.out.println("Error while reading user input"); endTime = System.currentTimeMillis(); userTime = endTime - startTime; System.out.println("It took you " + userTime + " milliseconds"); } //end static main } //end class CountTime counter

29 2. java.io

30 Example 2 :Write a String to a File
import java.io.*; public class WriteString { public static void main(String args[]) { String myString; DataOutputStream myStream; myString = "A Java String"; try { myStream = new DataOutputStream(new FileOutputStream("c:\\temp.dat")); myStream.writeChars(myString); myStream.close(); } catch (Exception e) { System.out.println("Error while writing to file"); } //end static main } // end WriteString class

31 java.util

32 Example 3: Using a Vector
import java.util.Vector; public class VectorIterator { public static void main(String args[]) { Vector myVector; String myString1 = "String one"; String myString2 = "String two"; String myString3 = "String three"; myVector = new Vector(); myVector.addElement(myString1); myVector.addElement(myString2); myVector.addElement(myString3); for (int i=0; i<myVector.size(); i++) { System.out.println( ((String) myVector.elementAt(i)).toUpperCase() ); } } //end static main } //end VectorIterator class Vector

33 java.net

34 Example 4: Fetch and print the first 30 lines of an HTML page
import java.io.*; import java.net.URL; public class URLReader { public static void main(String args[]) { URL myURL; DataInputStream myURLContent; try { myURL = new URL(" myURLContent = new DataInputStream(myURL.openStream()); for (int i=0; i<30; i++) { System.out.println(myURLContent.readLine()); } catch (Exception e) { System.out.println("Error while opening URL"); www.

35 java.awt -Graphics -Components -LayoutManagers

36 Example 5: A simple GUI example (part A)
import java.awt.*; public class AWTDemo extends Frame { private Panel myPanel; private Button myButton; public AWTDemo() { this.setBounds(0, 0, 200, 200); myPanel = new Panel(); myPanel.setBackground(Color.red); this.add(myPanel); myButton = new Button(); myButton.setBounds(250, 250, 300, 300); myButton.setLabel("Click me!"); myPanel.add(myButton); } // end constractor

37 Example 5: A simple GUI example (part B)
public static void main(String args[]) { AWTDemo myFrame; myFrame = new AWTDemo(); myFrame.show(); } //end static main public boolean handleEvent(Event myEvent) { if (myEvent.id == Event.WINDOW_DESTROY) { hide(); System.exit(0); return true; } if (myEvent.target == myButton && myEvent.id == Event.ACTION_EVENT) { if (myPanel.getBackground() == Color.red) { myPanel.setBackground(Color.blue); else myPanel.setBackground(Color.red); } //end if return super.handleEvent(myEvent); } //end handleEvent } //end class AWTDemo

38 Summary A lot of Java’s power comes from its packages.
java.lang contains language classes : System, String, Number, Math, Number etc. java.util contains collections and utils : Vector, Hashtable, Random, StringTokenizer. java.net contains network classes : URL, URLConnection, HTTPConnection, Socket. java.io contains stream classes and I/O : File, InputStreams, OutputStreams, Stream Tokenizer. java.awt contains all the Windowing classes : Components, Containers, Layouts, Events.

39 Quiz Why the String class is Final?
How can you make sure that a File object exists and can be read? Is it better to use an Array or a Vector to store objects? Can you imagine what would we need to do to write a simple web browser?

40 Exercises Write programs to :
count and print the time in milliseconds for 1000 printing statements. count the time of an html page download. randomly generate 100 integers, put them to a Vector and find their average. extract the HTTP addresses of links contained in a HTML page and print them along with the name of the link. initiate the downloading and parsing process after pressing a gui “Go” button.

41 Applets and Applications
Basic Level day 2 Part C Applets and Applications Athanasios Tsintsifas, LTR, University of Nottingham, http:

42 Aims Understand the differences between a Java Application and a Java Applet. Invoke Applets from HTML pages. Learn Applet’s major methods. Learn how to paint into an Applet. Create simple interaction using Events. Configure Applets externally. Place applets into applications.

43 Applets - Applications
Applets = Small Applications. placed on HTML pages, downloaded by the browser, executed on the browser’s JVM, severe security restrictions, four entry point methods, characteristics of a container for components. Gui Applications = Normal Applications. execute by the interpreter, no security restrictions, one “static public main(String[] argv)” entry point, need to instantiate a subclass of Frame or Window.

44 ...and has a lengthy hierarchy chain
Applets Basics Applet is a class in java.applet Object Component Container Applet Panel ...and has a lengthy hierarchy chain The Smallest Applet : import java.applet.*; public class My_Applet extends Applet { }

45 HTML containing Applets
<head> <title> My Applet </title> </head> <body> My First Applet <applet code = “MyApplet” height=“100” width=“200”> </applet> </body> </html> Applet lines

46 Applets Apps and the JVM

47 Applet : Important methods
Method Name Called when it.. init() -> is first loaded start() -> is viewable on the web page stop() -> stops been viewable destroy() -> needs to stop completely paint(Graphics g) -> needs to be painted update() -> needs to be painted

48 Applet : A first Example
import java.awt.*; import java.applet.*; public class HWApplet extends Applet { static final String message = "Hello World!"; private Font myFont; public void init() { myFont = new Font("Helvetica", Font.BOLD, 48); setSize(350,130); }

49 Applet : A first Example
public void paint(Graphics g) { // draw the black border of rectangle. g.setColor(Color.black); g.drawRect(9, 9, 332, 102); g.drawRect(8, 8, 334, 104); g.drawRect(7, 7, 336, 106); // lightgray rectangle g.setColor(Color.lightGray); g.fillRect(10, 10, 330, 100); // set the Helvetica font g.setFont(myFont); // draw the shadow of the text g.setColor(Color.gray); g.drawString(message, 40, 75); // draw the text g.drawString(message, 37, 72); } } // end class

50 Painting into Graphics
Most commonly used methods : drawLine(x1, y1, x2, y2) drawOval(x, y, width, height) drawRect(x, y, width, height) drawString(str, x, y) setColor(Color) setFont(Font) fillRect(x, y, width, height) draw3DRect(x, y, width, height, raised) drawRoundRect(x, y, w, h, arcWidth, arcHeight) 0,0 x y

51 Painting into Graphics Example
import java.awt.*; import java.applet.*; public class ShapesApplet extends Applet { static final String message = "Shapes!"; private Font myFont; public void init() { myFont = new Font("Helvetica", Font.BOLD, 36); } public void paint(Graphics g) { g.setColor(Color.black); g.setFont(myFont); // set the Helvetica font g.drawString(message, 150, 30); // draw the text g.drawRect(10, 50, 80, 50); g.fillRect(10, 130, 80, 130); // draw 2 rectangles

52 Painting into Graphics Example
g.drawLine(100, 50, 180, 100); // draw one line int[] xPoints = {100, 120, 135, 160, 130}; int[] yPoints = {70, 100, 160, 180, 100}; g.drawPolyline(xPoints, yPoints, 5); // draw one polyline g.drawRoundRect(200, 50, 70, 50, 30, 30); g.fillRoundRect(280, 50, 100, 50, 30, 30); // draw 2 Round rectangles g.drawOval(200, 130, 50, 80); // draw an oval g.fillOval(270, 130, 100, 100); // fill an oval // draw 2 arcs g.drawArc(100, 200, 50, 70, 100, 100); g.fillArc(150, 200, 80, 100, 130, 130); } } // end class

53 Event Handling Simply An event signals that something happened.
Events can be triggered by : The user, using : the mouse, the keyboard. The system, notifying changes Programmers exploit events by attaching special handling code which responds when an event occurs.

54 Mouse Events Mouse events get generated when the mouse is used.
We can override several methods to provide handling : mouseEnter (Event e, int x, int y) mouseMove (Event e, int x, int y) mouseExit (Event e, int x, int y) mouseDown (Event e, int x, int y) mouseUp (Event e, int x, int y) mouseDrag (Event e, int x, int y)

55 Keyboard Events Similar to mouse Events.
Two main methods to override : keyDown (Event e, char c) keyUp (Event e, char c) We get the int value of the ASCII char. We test for special keys by checking : Event.xx (xx = UP, END, PGDN, etc).

56 A Scribble Example import java.awt.*; //Import Classes of awt
public class Scribble extends Frame { private int last_x, last_y; //Last coordinate public Scribble(String _name) { super(_name); //To pass the title } // This method gets called each time the user // clicks on our Scribble-Frame public boolean mouseDown(Event e, int x, int y) { last_x = x; last_y = y; return true; } // end mouseDown

57 A Scribble Applet Example
// This method gets called each time the user // drags the mouse on our Scribble-Frame public boolean mouseDrag(Event e, int x, int y) { Graphics g = this.getGraphics(); g.drawLine(last_x, last_y, x, y); last_x = x; last_y = y; return true; } // end method mouseDrag //This is the “entry point” where we instantiate an object //of type Scribble public static void main(String args[]) { Scribble my_scribble = new Scribble("Example Scribble"); my_scribble.resize(200,200); my_scribble.show(); } // end main } //end Class Scribble

58 Passing Values from HTML
<applet code = “MyApplet” height=“100” width=“200”> <param name=colour value=blue> </applet> Applet String extColour = getParameter(“colour”); What can we do to read other values than Strings?

59 Security Restrictions for Applets
No File open/save, No Sockets to anywhere except the origin’s server, No processes and execution of other programs, No replacing or tampering the Security manager, No Native methods.

60 Placing an Applet in an Application
Just need to : create a Frame, instantiate the applet, add the applet to the Frame, call : init(), start(), stop(), destroy() appropriately. You can do this because Applet is a Component.

61 Summary Differences between Applications and Applets.
HTML tags for Applets. Important Applet methods. Painting into Applets. Simple Events handling. Parameterising Applets. Using applets into applications.

62 Quiz Is it possible to place an Applet inside another Applet?
Is it possible to start a Frame from an Applet? Class Graphics does not contain a method to set a pixel to a specific colour. How would you do it? What will happen if you try to draw a shape which exceeds the limits of the applet’s bounds?

63 Exercises Write a simple applet that draws a red rectangle, create its HTML page and execute it with the help of the appletviewer. Extend the previous applet to get its rectangle bounds from the HTML page. Write an applet that lets the user click and drag the mouse to create randomly coloured circles. Make the previous applet able to paint other shapes as well as circles.

64

65 Focusing on learning Java
Basic Level day 2 Part D Focusing on learning Java Athanasios Tsintsifas, LTR, University of Nottingham, http:

66 Aims Learn how to improve your Java skills.
Know the ten most common mistakes on java. Find out where to look for info, what to use for development and how to troubleshoot an error. Try the large exercise.

67 Difficulties Learning Java
To master Java you need to know : How to solve problems algorithmically using Java’s syntax and environment. The various classes contained in Java’s packages and how to use them. The OO model and the design behind Java’s classes.

68 How to improve Read other people’s code.
Experiment with the language itself. Experiment with all the basic classes. Read Java’s source code. Write the same program from scratch each time trying a different way. When you find yourself spending a significant amount of time designing over implementing it’s time to start learning OOD methods and Design Patterns.

69 The 10 most common bugs Missing ( ) [ ] : Unpredictable error messages
Forgotten Imports : Class not Found A Class for an Object: Method not found (if not static) Spelling mistake : Various error messages Wrong Signature : Wrong type of Arguments Return nothing = void: Invalid method declaration Wrong equality : Incompatible type for if Endless loops : Program seems to be hanged Many public classes : Public class x must be defined in a file called ”x.java" Trusting your code without testing!

70 Where to find info Web Links http:// java.sun.com/ www.gamelan.com
Magazines Java-Report, Application Developer, Dr. Dobbs.

71 What to use : Books : IDE’s
Thinking in Java, Prentice-Hall 1998, ISBN: Java in a Nutshell, O’Reilly, 1997, ISBN: X IDE’s Symantec’s Vcafe 4, IBM’s VisualAge 3, Borland’s Jbuilder 3, Sun’s Forte.

72 How to troubleshoot Debug either using a debugger or print statements.
Try to isolate and identify the error’s source. Sometimes -not very often- it is not your fault and you bumped into a genuine Java bug. In this case, it is quite likely that other people have already found a workaround. Search the Usenet and specially : comp.lang.java.programmer comp.lang.java.api comp.lang.java.tech comp.lang.java.security comp.lang.java.setup comp.lang.java.misc

73 Summary The few only ways to improve your Java skills.
Ten of the most common mistakes. What to read and what to use. How to troubleshoot those hard to find errors.

74 Exercise To integrate the knowledge obtained in the previous section be creative! Programming can be fun; you could try for instance to create a small game. By now, you should be able to write a variety of simple games like hangman, tic-tac-toe, memory, or any cards game. Lets decide on a game and try to think logically on its implementation.

75

76 The End Java Basic Level day2


Download ppt "Exception Handling, Packages"

Similar presentations


Ads by Google