Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.

Slides:



Advertisements
Similar presentations
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Advertisements

Yoshi
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Files and Streams CS 21a Chapter 11 of Horstmann.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Files and Streams CS 21a. 10/02/05 L18: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Introduction to Object-Oriented Programming
Introduction to Java and Object-Oriented Programming AJSS Computer Camp Department of Information Systems and Computer Science Ateneo de Manila University.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Data Structures and Java CS 105. L7: Java Slide 2 Data structure Data structure defined: A systematic way of organizing and accessing data Examples Dictionary:
Classes CS 21a: Introduction to Computing I First Semester,
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Files and Streams CS /02/05 L7: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Data Structures and Java CS /14/2015 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved. L6:
Using Objects. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L7: Objects Slide 2 Java.
Java Programming Review (Part II) Enterprise Systems Programming.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
LECTURE 8: EXCEPTIONS CSC 212 – Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Arrays and Array Lists CS 21a. Problem 1: Reversing Input Problem: Read in three numbers and then print out the numbers in reverse order Straightforward.
Exception Handling How to handle the runtime errors.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Chapter 10 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Introduction to Exceptions in Java
CMSC 202 Exceptions.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Classes CS 21a: Introduction to Computing I
Exceptions.
Exceptions 10-May-19.
Java Basics Exception Handling.
Exceptions.
Presentation transcript:

Odds and Ends

CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Odds and Ends Some small topics on the side … Basic Exception Handling Class variables (static methods and fields) Command-line arguments Input through JOptionPane

Exceptions

CS 21a 09/18/05 L14: Odds & Ends Slide 4 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Basic Exception Handling Exception: something unexpected that can occur in the execution of a program wrong number format NullPointerException ArrayIndexOutOfBoundsException divide by zero attempt to open a file that does not exist etc. Java provides a way to handle exceptions that are thrown: the try-catch statement

CS 21a 09/18/05 L14: Odds & Ends Slide 5 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Try-catch Statement Syntax: try { … } catch ( Exception e ) {... } Example: try { System.out.println( 5 / x ); } catch ( Exception e ) { System.out.println( “div by zero” ); } Note the formatting convention.

CS 21a 09/18/05 L14: Odds & Ends Slide 6 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Breaking out of the try Block try { statement1; statement2; // if exception occurs here, // statement3 will be skipped statement3; } catch ( Exception e ) { statement4; // executed after exception occurs }

CS 21a 09/18/05 L14: Odds & Ends Slide 7 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Try-catch Chain try { … file operation … } catch( FileNotFoundException se ) { … if file is not found … } catch( EOFException ee ) { … if no more data to read … } catch( IOException e ) { … for all other cases not yet covered … } … you can catch “Exception” to catch any kind of Exception works because of polymorphism OR … You can use a “try-catch chain” to catch specific exceptions

CS 21a 09/18/05 L14: Odds & Ends Slide 8 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Ignoring exceptions Some exceptions do not need to be caught but will generate a runtime error if they occur Examples: NullPointerException, ArrayIndexOutOfBoundsException If enclosed in a try-catch statement, users can choose to handle them Other exceptions need to be caught Examples: when dealing with Input/Output You may either: enclose the statements in a try- catch statement and handle the situation or place the clause throws Exception at the end of the method header (recall console.readLine() example)

CS 21a 09/18/05 L14: Odds & Ends Slide 9 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved More on Exceptions (CS 21b) Stuff we’ll discuss in more detail in CS 21b Different types of Exceptions Generating your own exceptions Other features Don’t worry about these for now!

Class (static) variables and methods

CS 21a 09/18/05 L14: Odds & Ends Slide 11 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Class (static) fields and methods Things we’ve seen, but not fully explained Built-in Constants Math.PI, FlowLayout.CENTER, Color.green, etc. Built-in functions Math.sqrt(), Math.abs(), Integer.parseInt(), Double.isNaN() Static methods public static void main( String[] args ) Static fields your own constants public static final int MY_CONSTANT These are all “static” fields or methods

CS 21a 09/18/05 L14: Odds & Ends Slide 12 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Static Fields means that the field is shared by all instances of the same class aka “class variable” as opposed to “instance variable” e.g., in BankAccount, balance is an “instance variable” – each instance has its own independent copy However, if all BankAccounts share a minimum balance value, we can make a static field for that

CS 21a 09/18/05 L14: Odds & Ends Slide 13 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Example: Minimum Balance Account SV129 Account SV506 Account SV008 balance Account minBalance There is one copy of minBalance for the whole class and shared by all instances. The Account class instances of the Account class

CS 21a 09/18/05 L14: Odds & Ends Slide 14 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Static Methods Normally, a method applies to a particular instance e.g., you can’t just call deposit() from an applet. (Which account are you deposting to?) you have to call aliceAccount.deposit(), where aliceAccount is a pre-existing BankAccount a static method is a method that does not refer to a particular instance That’s why we call them using ClassName.methodName() there’s no instance that “owns” it. It “belongs” to the class in BlueJ, we right-click on the class, not on the instances Useful for “functions” that don’t depend on an instance e.g., Math.sqrt( double d ) Note: they cannot refer to instance variables can only use static fields and methods that’s why convenience methods used by main have to be static

CS 21a 09/18/05 L14: Odds & Ends Slide 15 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved public class BankAccount { private static int curNum = 0; private int balance; public BankAccount( int initBal ) { balance = initBal; BankAccount.curnum++; } public void deposit( int amount ) { balance += amount; } public void withdraw( int amount ) { balance -= amount; } public int getBalance() { return balance; } Another example In this code, we use the static field curNum to keep track of the number of BankAccounts created. Whenever we create a bank account, the value of curNum increases by 1. CurNum is accessible by all instances of BankAccount

Command-Line Arguments

CS 21a 09/18/05 L14: Odds & Ends Slide 17 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Using command-line arguments Arguments entered from the command line e.g. java InputSampler abc 123 “abc” and “123” are command-line arguments public static void main( String[] args ) String[] args stores these arguments args.length = 0 if no arguments are entered args.length = 2 if you run the example above Usage String x = args[0]; //if args.length > 0

CS 21a 09/18/05 L14: Odds & Ends Slide 18 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Using command-line arguments Very easy and straightforward to use. No need to include classes. Only takes in Strings. You will need to convert to ints or doubles, if needed. Works only if you put in command-line arguments. Otherwise, you get an ArrayIndexOutOfBounds exception if you try to access an index that does not exist. Hence, the need to check for the length of the array.

JOptionPane

CS 21a 09/18/05 L14: Odds & Ends Slide 20 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Using JOptionPane import javax.swing.*; String showInputDialog( String prompt ) Usage: String x = JOptionPane.showInputDialog ( “Enter string: ” );

CS 21a 09/18/05 L14: Odds & Ends Slide 21 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Using JOptionPane Provides a nice GUI window for user to provide input, when in a Java application Need to import javax.swing to use it Only takes in Strings. You will need to convert to ints or doubles, if needed. Need to call System.exit( 0 ); at the last line of main() so that the program exits