1 Java coding conventions Lecture 2. 2 Please read Not only on assignment 1, but always. 80% of the lifetime.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
CS102--Object Oriented Programming
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Index Exception handling Exception In Java Exception Types
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Advanced Java Course Exception Handling. Throwables Class Throwable has two subclasses: –Error So bad that you never even think about trying to catch.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
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.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
1 Web Based Programming Section 6 James King 12 August 2003.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Object Oriented Programming
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Slides Credit Umair Javed LUMS Web Application Development.
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.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
The Java Programming Language
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
FIRST JAVA PROGRAM. JAVA PROGRAMS Every program may consist of 1 or more classes. Syntax of a class: Each class can contain 1 or more methods. public.
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.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Software Documentation Section 5.5 ALBING’s Section JIA’s Appendix B JIA’s.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Exceptions and Assertions Chapter 15 – CSCI 1302.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
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.
More Sophisticated Behavior
Logger, Assert and Invariants
Java Programming Language
Exception Handling Chapter 9 Edited by JJ.
Web Design & Development Lecture 7
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

1 Java coding conventions Lecture 2

2 Please read Not only on assignment 1, but always. 80% of the lifetime cost of a piece of software goes to maintenance. Hardly any software is maintained for its whole life by the original author. Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly. If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create.

3 The javadoc tool … generates HTML documentation directly from doc comments in your Java source code. /* * Not a doc comment */ /** * A doc comment */

4 Javadoc example package examples.intro; /** * class to demonstrate assert facility of J2SDK v1.4 */ public class AssertTester { /** * main method of AssertTester prints program * arguments to System.out args[] command line arguments java.lang.AssertionError * occurs if no argument are supplied * or an argument has more than 3 characters */ public static void main(String[] args) {... } }

5 Other comments Line comment // blabla til end of line java code // blabla til eol Block comment /* blabla */

6 Common Javadoc variable_name args[] command line index index number of element. maximum value of the two complete_classname com.ifor.util.FallIntoLakeException blablabla See page in the book.

7 Contained classes Lecture 2

8 Enclosed classes A class may be defined inside the definition of another class Depending on how it is defined, it falls into one of 4 categories Nested top-level class Member inner class Local inner class Anonymous local inner class

9 Nested top level class are declared with the keyword static. Although it is contained within another class, it has the same behavior as ordinary top-level classes. It is just an alternative grouping method similar to a package.

10 Nested top level class example public class Graph1 { public void addNode( int x, int y ) { Node n = new Node( x, y ); } public static void main( String[] args ) { Graph1 g = new Graph1(); g.addNode( 4, 5 ); g.addNode( -6, 11 ); } private static class Node { private int x, y; public Node( int x, int y ) { this.x = x; this.y = y; } } // end of Node class } // end of Graph1 class

11 Member inner class Not declared as static. Must be instantiated as part of an instance of their enclosing class. Enclosing e = new Enclosing(); Inner i1 = e.new Inner(); Inner i2 = e.new Inner(); /* i1 and i2 both has access to members in e */ A member inner class is a qualified member of the enclosing class

12 Local inner classes Are defined within a method. Their definition is private to that method. But they have full access to the members of the enclosing class

13 Local inner classes Example public class Equation2 { > public Result getResult( final int input1, final int input2 ) { final int[] localVar = { 2,6,10,14}; return new Result() { private int normalField; public double getAnswer() { return (double) input1/input2 - normalField; } // this is an instance initializer block { normalField = 2; } }; } }

14 Anonymous inner classes Are local inner classes that do not have a name. Are created with the enhanced syntax of the new keyword. New [class_name()] {body_of_class}

15 Read more in the book In Chapter 2 Sooner or later you will encounter code that exploits nested and inner classes.

16 Exceptions Lecture 2

17 Basic pattern for handling Exceptions try{ doSomething(); somethingMore(); evenMore(); } catch (someException e) { bla(); } catch (otherException e) { bla(); bla(); } finally { always(); }

18 Checked / Unchecked Exception Most Exceptions must be handled (i.e. either declared in the method’s throws clause or caught) Except Runtime Exceptions, which are “unchecked” – they don’t have to be declared

19 Two ways To throw: > >( >) throws > { > } To catch: > >( >) { try { > } catch ( > >) { > }

20 When to do what? If code that your code calls declares that it can throw an Exception, what should you do? Just throw the exception Catch the exception, report it, and recover Catch the exception, make a new, different exception, and throw the new one When do you throw an Exception even if no Exception was thrown to you?

21 When to re-throw the Exception If it’s more appropriate to deal with it at a higher level of the code. If the exception means death to the method it’s in. In other words, there’s no reasonable way you can continue to execute the code of this method.

22 When to catch it and recover If this is the appropriate place to report the exception to the user, or log it, or whatever you plan to do with it. If you can and should continue with this method – for example if you can use a default value, or try again.

23 When to catch it & throw your own If you’re sure the Exception is impossible (your code is correct), so you don’t want to have to declare it all the way up. On the other hand, if your code is incorrect, you should not “hide” the exception – you need to see it so that you can fix your programmer error. Throw a new RuntimeException, or your own sub class of RunTimeException.

24 When to create your own Exception Sometimes you might create a new Exception instance even though none of your code threw one to you. You might be the first “thrower” of this Exception. You should do this if your code detects some error state that you cannot recover from in this method – for example, an input might be of an illegal value.

25 Use of Exceptions When handling critical events that may jeopardize the system stability or worse. Obvious Feedback to the caller Should we throw an Exception when the user inputs data with wrong syntax? What’s your point of view? Depends on the context? Is the fine line fuzzy and gray again?

26 Checked or Unchecked? If you create your own new Exception class, should it be checked or Runtime? RuntimeExceptions are for programmer error i.e. your code is in a bad state. Stop program execution and go debug. By the time a program reaches an end-user, it should never throw these. The outermost layer of your program should gracefully catch all Exceptions, even Runtimes and do something user-friendly. Checked exceptions (all except RuntimeExceptions) are for dealing with the outside world. If something about the input the user gave you is bad, or a file is corrupt, or a database server is down, these are real-life things that could happen, and your program should cope with them as gracefully as possible.

27 Summary of Exceptions Catch and hide an exception if Can recover: (default value, user try again) Re-throw an exception if Irrecoverable to method More appropriate to handle elsewhere Throw new if You receive a checked exception and want to throw an unchecked runtime exception

28 Summary of Exceptions When creating your own exception class Name it descriptively Place appropriately in class heirarchy If programmer error, make it a subclass of RuntimeException (so it’s unchecked) If outside error (network, user, etc.), make it a checked Exception

29 Assignment 1 Lecture 2

30 getMethods() ? Question yesterday: Why does getMethods() return many methods when the class contain no methods at all? Read the API documentation for that method thoroughly and you will find out. Or even ask your peers, but not immediatelly. (and mention it in the report if the help was significant).

31 Interfaces What constitutes a constant field in an interface? “Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.” From the language specification. The assignment specification tells us what fields to consider “constant”, and thus to be included in the interface: “final”