Download presentation
Presentation is loading. Please wait.
Published byColeen Hutchinson Modified over 8 years ago
1
Intro to Computer Science Class #8 Exceptions and I/O Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj, Isaiah, Allison, Thibault University of Pennsylvania 9 April 2008
2
Today’s Agenda Quiz Discussion Exceptions File I/O Focused on Cryptography
3
Discussion Let’s talk about cryptography!
4
Introduction The world is full of bad (dumb ?) people wanting to crash your program Here come Exceptions The world is full of nosy people wanting to see what you’re doing Here comes Cryptography
5
Contract A good input, fulfilling some conditions Program A correct output An incorrect input Program ????
6
What shall we do ? Any ideas on what we should do ? –Error message –Default value –Error value –Kill the user Java provides a very efficient way of dealing with this
7
Exceptions Already seen some of them: NullPointerException, ArrayIndexOutOfBoundException An exception is: –An object created by methods when there is a problem. –When this object is created, the method exits immediately and “throws” it toward the user. –If no methods try to catch it, it will “hit” the user and display the error message.
8
Let’s throw one … Enough with the theory, we want to see some red nasty errors! > int data[] = new int[10]; > data[666] = 0; What will happen ?
9
Demo: carelessMethod public class SimpleClass{ public int carelessMethod(int n){ int sum=0; int i = 1; while(i!=(n+1)){ sum+=i; i++; } return sum; } public class SimpleClass{ public int carelessMethod(int n){ int sum=0; int i = 1; while(i!=(n+1)){ sum+=i; i++; } return sum; }
10
My own exception public class NegativeException extends Exception{ public NegativeException(int num){ // call the constructor of the super class // (in this case, Exception) super("Negative ” +num+ " not allowed..."); } public class NegativeException extends Exception{ public NegativeException(int num){ // call the constructor of the super class // (in this case, Exception) super("Negative ” +num+ " not allowed..."); } It HAS to extend Exception to be thrown Usually, we say why we caused the exception, just by using super(). What is super() ?
11
How to throw one ? public void myFunction throws ArrayIndexOutOfBoundsException{ // Some Code throw new ArrayIndexOutOfBoundsException(); // Some Code } public void myFunction throws ArrayIndexOutOfBoundsException{ // Some Code throw new ArrayIndexOutOfBoundsException(); // Some Code }
12
How to throw one ? public void myFunction throws NegativeException{ // Some Code throw new NegativeException(“something”); // Some Code } public void myFunction throws NegativeException{ // Some Code throw new NegativeException(“something”); // Some Code } I can also throw my own exception !
13
Demo: carelessMethod public class SimpleClass{ public int carelessMethod(int n) throws NegativeException { int sum=0; int i = 1; if(n<=0){ throw new NegativeException(n); } while(i!=(n+1)){ sum+=i; i++; } return sum; } public class SimpleClass{ public int carelessMethod(int n) throws NegativeException { int sum=0; int i = 1; if(n<=0){ throw new NegativeException(n); } while(i!=(n+1)){ sum+=i; i++; } return sum; } Or any class extending the class Exception Create a new Exception and throw it We have to declare that this method might cause an exception
14
try/catch Perhaps we want to fix the error ourselves … –catch it before it reaches the user, and do something appropriate –Syntax: try{…} –Syntax: catch(NegativeException n){ … } –Don’t bother too much about these for now, catching is used mainly for file I/O
15
Demo: carefulMethod public class SimpleClass { public int carefulMethod(int n) throws NegativeException { int sum=0; try{ sum = carelessMethod(n); System.out.println(“All done”); } catch(NegativeException e){ System.out.println(“Please Try again”); } return sum; } public class SimpleClass { public int carefulMethod(int n) throws NegativeException { int sum=0; try{ sum = carelessMethod(n); System.out.println(“All done”); } catch(NegativeException e){ System.out.println(“Please Try again”); } return sum; }
16
Now lab… Go to http://www.seas.upenn.edu/eas285/forSLA Students/lectures/lecture8_ExceptionsIO/l ab1.html Work in pairs -Goal: LET’S CRASH OUR PROGRAMS !!
17
Demo: carefulMethod public class SimpleClass { public int carefulMethod(int n) throws NegativeException { int sum=0; try{ sum = carelessMethod(n); System.out.println(“All done”); } catch(NegativeException e){ System.out.println(“Please Try again”); } return sum; } public class SimpleClass { public int carefulMethod(int n) throws NegativeException { int sum=0; try{ sum = carelessMethod(n); System.out.println(“All done”); } catch(NegativeException e){ System.out.println(“Please Try again”); } return sum; }
18
You know I/O. Yes, you do. Remember: –System.out.println –Used to print strings on the screen System.out is doing some I/O One major concept of I/O are streams
19
0101010010 What is a stream ? My Program The Screen My Hard disk The Keyboard 0101010010 Streams System.in System.out + System.err
20
What is ascii ??
21
Using Java Predefined Classes Input and Output is long, complicated, and luckily Java has written a class that we can use to do it ! We will use java predefined classes and use import How to search for classes ? Little demo using google
22
File I/O We need to access files: - we can’t always rely on the user for input; - we can’t even use the user for some input (image processing, etc…) - we might want to save variables for the next use To access Files, we need to do a few things: - create a File object - create a stream to this file object - play with the stream, write/read - close the stream
23
Create a File object How to create an instance ? (remember: import java.io.File) File f = new File(“path_to_file”); Hint: how to know your working directory ? System.getProperty("user.dir"); Example and playing with a file object (try typing this in Interaction Pane): File f = new File(“my_text.txt”); f.exists(); f.getPath(); f.length(); // For more, look on the web :)
24
How to read a file? FileInputStream How to create an instance ? FileInputStream fs = new FileInputStream(f); How to read from it ? int i = fs.read(); How to close it ? fs.close(); Important: if int i = fs.read() == -1 ; it means that we reached the end of the file. A B C D E F G H I J K L i 65 66
25
How to read a file? FileInputStream Basic example, reading a file and printing it to the screen import java.io.*; File f = new File(“my_text.txt”); FileInputStream fs = new FileInputStream(f); int data = fs.read(); // an int because it’s the ascii code of it while(data>=0){ // if data == -1 End of the file System.out.write(data); // System.out.write is printing the character associated //with the ascii value given as argument data = fs.read(); } fs.close();
26
More classes ? We can use more advanced classes: StringBuffer : an object where we can append new characters to it, very useful for file reading FileReader: basically (for now) the same that FileInputStream URL : an equivalent of the File object but for webpages, has the function openStream() which returns an InputStream to that page, for example: import java.net.*; url = new URL(”http://www.google.fr“);”http://www.google.fr InputStream in = url.openStream(); int data = in.read(); while(data>=0){ System.out.write(data); data = in.read(); } in.close();
27
How to write to a file? FileOutputStream How to create an instance ? FileOutputStream fs = new FileOutputStream(f,True); // If the file exists, it will append data to the end. If the // file doesn’t exist, it will create it. How to write to it ? fs.write(i) How to close it ? fs.close(); i 65 AA
28
How to write to a file ? FileOutput Basic Example, writing “Hello world” to a text file import java.io.*; File f = new File(”text-file.txt”); FileOutputStream fs = new FileOutputStream(f); char[] c = “hello world”.toCharArray(); // What is that ?? for(int i=0;i<c.length;i++) { fs.write((int) c[i]); // And that ??? } fs.close();
29
Now lab… Go to www.seas.upenn.edu/eas285/forSLAStud ents/lectures/lecture8_ExceptionsIO/lab2. html www.seas.upenn.edu/eas285/forSLAStud ents/lectures/lecture8_ExceptionsIO/lab2. html Work in pairs too -Goal: encrypting and decrypting a string, read from a file and writing it to the file
30
Why did I talk about Exceptions? Usually when you try to access a File, there can be some problems (File not found, hard drive crash, computer exploded..) So you use … Exceptions! try{ // Opening the stream } catch(IOException e) { // Well, notify the user, fix the error }
31
More on encryption http://www.di-mgt.com.au/rsa_alg.html http://www.gax.nl/wiskundePO/# http://en.wikipedia.org/wiki/RSA http://en.wikipedia.org/wiki/Public-key_cryptography http://www.cs.princeton.edu/introcs/78crypto/RSA.java.html http://pajhome.org.uk/crypt/rsa/implementation.html www.cs.cityu.edu.hk/~cs4288/Java/RSA.doc Readings for the most-interested. (Extra credit if you can explain RSA to a cat)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.