Java Exceptions Java, winter semester

Similar documents
Java Strings Java, winter semester

JAVA V Source files Java, winter semester

2.6 Error, exception and event handling

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions

An overview of Java, Data types and variables

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

THE CONCEPT OF OBJECT

JDK 7 (2011.7) knight76.tistory.com Knight76 at gmail.com

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

CS260 Intro to Java & Android 03.Java Language Basics

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Java. Error, Exception, and Event Handling. Error, exception and event handling. Error and exception handling in Java

Introduction to Programming Using Java (98-388)

COE318 Lecture Notes Week 10 (Nov 7, 2011)

ITI Introduction to Computing II

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Java language. Part 1. Java fundamentals. Yevhen Berkunskyi, NUoS

ITI Introduction to Computing II

Exception-Handling Overview

Java Overview An introduction to the Java Programming Language

The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT

Index COPYRIGHTED MATERIAL

13: Error Handling with Exceptions. The basic philosophy of Java is that "badly formed code will not be run."

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Language Fundamentals Summary

Java Notes. 10th ICSE. Saravanan Ganesh

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Exceptions. Examples of code which shows the syntax and all that

Class, Variable, Constructor, Object, Method Questions

Java Identifiers, Data Types & Variables

Java Programming. Atul Prakash

Exceptions. CSC207 Winter 2017

National University. Faculty of Computer Since and Technology Object Oriented Programming

1 Shyam sir JAVA Notes

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Pace University. Fundamental Concepts of CS121 1

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Array. Prepared By - Rifat Shahriyar

Programming in C++ 4. The lexical basis of C++

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Programming II (CS300)

Sri Vidya College of Engineering & Technology Question Bank

Exceptions - Example. Exceptions - Example

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Java Basic Datatypees

JAVA Programming Fundamentals

Types, Values and Variables (Chapter 4, JLS)

Java Loose Ends. 11 December 2017 OSU CSE 1

What does this program print?

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

CSC Java Programming, Fall Java Data Types and Control Constructs

Fundamentals of Object Oriented Programming

COMP1008 Exceptions. Runtime Error

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

Java Programming Language Mr.Rungrote Phonkam

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

BBM 102 Introduction to Programming II Spring Exceptions

Exceptions and Libraries

EXCEPTION HANDLING. Summer 2018

COMP6700/2140 Data and Types

CS 3 Introduction to Software Engineering. 3: Exceptions

Software Practice 1 Basic Grammar

Points To Remember for SCJP

Declarations and Access Control SCJP tips

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Java Classes & Primitive Types

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

Java: introduction to object-oriented features

Java Classes & Primitive Types

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Array. Array Declaration:

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 290 / 321

Introduction to Programming (Java) 2/12

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

More on Exception Handling

About this exam review

c) And last but not least, there are javadoc comments. See Weiss.


Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

More on Exception Handling

Language Features. 1. The primitive types int, double, and boolean are part of the AP

6.096 Introduction to C++ January (IAP) 2009

3. Java - Language Constructs I

Timing for Interfaces and Abstract Classes

Chapter 14. Exception Handling and Event Handling ISBN

Programming II (CS300)

For more details on SUN Certifications, visit

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Transcription:

Java Exceptions 1

Exceptions errors reporting and handling an exception represents an error state of a program exception = an instance of java.lang.throwable two subclasses java.lang.error and java.lang.exception specific exceptions children of the above two classes java.lang.error "unrecoverable" errors should not be caught e.g. OutOfMemoryError java.lang.exception recoverable errors should (has to) be caught e.g. ArrayIndexOutOfBounds 2

Exception handling statement try/catch/finally try {... // a block of code where an exception // can happen and we want to handle it catch (Exception1 e) { // handling of exceptions with the // Exception1 type and its subtypes catch (Exception2 e) { // handling of exceptions with the // Exception2 type and its subtypes finally { // executes always 3

Exception handling if the exception is not caught in a block where it occurs, it propagates to the upper block if the exception is not caught in a method, it propagates to the calling method it the exception reaches main() and it not caught, it terminates the virtual machine information about the exception is printed 4

try/catch/finally in Java 7 interface AutoClosable and extended try example: class Foo implements AutoClosable {... public void close() { try ( Foo f1 = new Foo(); Foo f2 = new Foo() ) {... catch (...) {... finaly {... at the end of try (normally or by an exception), close() is always called on all the objects in the try declaration called in the reverse order than declared 5

multi catch (since Java 7) class Exception1 extends Exception { class Exception2 extends Exception { try { boolean test = true; if (test) { throw new Exception1(); else { throw new Exception2(); catch (Exception1 Exception2 e) {... 6

Exception declaration a method that can throw an exception must either catch the exception, or declare the exception via throws public void openfile() throws IOException {... it is not necessary to declare following exceptions children of java.lang.error children of java.lang.runtimeexception it extends java.lang.exception ex. NullPointerException, ArrayIndexOutOfBoundException 7

Throwing exceptions statement throw throws (generates) an exception "argument" a reference to Throwable throw new MojeVyjimka(); existing exceptions can be thrown but, commonly, own ones are used exceptions can be re-thrown try {... catch (Exception e) {... throw e; 8

Re-throwing (in Java 7) class Exception1 extends Exception { class Exception2 extends Exception { public static void main(string[] args) throws Exception1, Exception2 { try { boolean test = true; if (test) { throw new Exception1(); else { throw new Exception2(); catch (Exception e) { throw e; since Java 7 exceptions remember their types with Java 6, this cannot be compiled it would require throws Exception 9

java.lang.throwable has the field (private) typed String contains a detailed description of the exception method String getmessage() constructors Throwable() Throwable(String mesg) Throwable(String mesg, Throwable cause) // since 1.4 Throwable(Throwable cause) // since 1.4 methods void printstacktrace() 10

Own exceptions public class MyException extends Exception { public MyException() { super(); public MyException(String s) { super(s); public MyException(String s, Throwable t) { super(s, t); public MyException(Throwable t) { super(t); 11

Chains of exceptions... try {...... catch (Exception1 e) {... throw new Exception2(e);... throwing an exception as a reaction to another exception it is common reacting to a system exception by an own one 12

Suppressing exception in several cases an exception can suppress another one it is not chaining of exceptions! typically it can happen if an exception occurs in the finally block in the extended try block (Java 7) Throwable[] getsuppressed() method in Throwable returns an array of suppressed exceptions 13

JAVA Source files 14

Unicode programs ~ Unicode comments, identifiers, char and string contants the rest is in ASCII (<128) or Unicode escape sequences < 128 Unicode escape sequences \uxxxx \u0041... A the expanded sequence is not used for following ones \u005cu005a results in six chars \ u 0 0 5 a 15

Source code file processing 1.translation of unicode escape sequences (and all of the source code) into a sequence of unicode chars 2.the sequence from (1) is translated into a sequence of chars and line-terminating chars 3.the sequence from (2) is translated into a sequence of input tokens (without white-spaces and comments) line-terminating chars CR LF CR LF 16

Test public class Test { public static void main(string[] argv) { int i = 1; i += 1; // is the same as \u000a i = i + 1; System.out.println(i); Program prints out: a) 1 b) 2 c) 3 d) cannot be compiled e) a runtime exception 17

Encoding argument of javac -encoding encoding of source files without it default encoding 18

Literals integer literals decimal 0 1 23-3 hexadecimal... 0xa 0xA 0x10 octal 03 010 0777 binary... 0b101 0B1001 since Java 7 by default of the int type long... 1L 33l 077L 0x33L 0b10L floating-point literals 0.0 2.34 1..4 1e4 3.2e-4 by default double float... 2.34f 1.F.4f 1e4F 3.2e-4f boolean literals true, false 19

Literals underscores in numerical literals since Java 7 for better readability 1234_5678_9012_3456L 999_99_9999L 3.14_15F 0xFF_EC_DE_5E 0xCAFE_BABE 0x7fff_ffff_ffff_ffffL 0b0010_0101 0b11010010_01101001_10010100_10010010 20

Literals char literals 'a' '%' '\\' '\'' '\u0045' '\123' escape sequences \b \u0008 back space \t \u0009 tab \n \u000a line feed \f \u000c form feed \r \u000d carriage return \" \u0022 \' \u0027 \\ \u005c 21

Literals String literals "" "\"" "this is a String" null literal 22

JAVA Main program (the method main) 23

main void main(string[] args) arguments args ~ command-line arguments contains arguments only does not contain the name of a program as in C/C++ return value of the program System.exit(3); return type of the method void 24

JAVA Inner classes 25

Inner classes defined in the body of another class public class MyClass { class InnerClass { int i = 0; public int value() { return i; public void add() { InnerClass a = new InnerClass(); 26

Inner classes the inner class can return a reference to the outer class public class MyClass { class InnerClass { int i = 0; public int value() { return i; public InnerClass add() { return new InnerClass(); public static void main(string[] args){ MyClass p = new MyClass(); MyClass.InnerClass a = p.add(); 27

Hiding inner class inner class can be private or protected access to it via an interface public interface MyIface { int value(); public class MyClass { private class InnerClass implements MyIface { private i = 0; public int value() {return i; public MyIface add() {return new InnerClass();... public static void main(string[] args) { MyClass p = new MyClass(); MyIface a = p.add(); // error - MyClass.InnerClass a = p.add(); 28

Inner classes in methods an inner class can be defined in method or just a block of code visible just in the method (block) public class MyClass { public MyIface add() { class InnerClass implements MyIface { private i = 0; public int value() {return i; return new InnerClass(); public static void main(string[] args) { MyClass p = new MyClass(); MyIface a = p.add(); // error - MyClass.InnerClass a = p.add(); 29

Anonymous inner classes public class MyClass { public MyIface add() { return new MyIface() { private i = 0; public int value() {return i; ; public static void main(string[] args) { MyClass p = new MyClass(); MyIface a = p.add(); 30

Anonymous inner classes public class Wrap { private int v; public Wrap(int value) { v = value; public int value() { return v; public class MyClass { public Wrap wrap(int v) { return new Wrap(v) { public int value() { return super.value() * 10; ; public static void main(string[] args) { MyClass p = new MyClass(); Wrap a = p.wrap(5); 31

Anon. inner classes: initialization elements outside an anon. in. class necessary in the anon. in. class final without final compile-time error since Java 8 - effectively final is enough i.e. declared without the final modifier, but there are no changes to the particular element public class MyClass { public MyIface add(final int val) { return new MyIface() { private int i = val; till Java 7 final is public int value() {return i; necessary here ; since Java 8 final can be omitted as there are no changes to val 32

Anon. inner classes: initialization anon. inner classes cannot have a constructor because they are anonymous object initializer public class MyClass { public MyIface add(final int val) { return new MyIface() { private i; { if (val < 0) i = 0; else i = val; public int value() {return i; ; 33

Relation of inner and outer class the instance of an inner class can access all elements of the instance of the outer class interface Iterator { boolean hasnext(); Object next(); public class Array { private Object[] o; private int next = 0; public Array(int size) { o = new Object [size]; public void add(object x) { if (next < o.length) { o[next] = x; next++; // cont... 34

Relation of inner and outer class // cont... private class AIterator implements Iterator { int i = 0; public boolean hasnext() { return i < o.length; public Object next() { if (i < o.length) return o[i++]; else throw new NoNextElement(); public Iterator geiterator() { return new AIterator(); 35

Relation of inner and outer class a reference to the instance of the outer class OuterClassName.this previous example classes Array and AIterator the reference to the instance of Array from Array.AIterator Array.this 36

Relation of inner and outer class creation of the instance of an inner class outside of its outer class public class MyClass { class InnerClass { public static void main(string[] args) { MyClass p = new MyClass(); MyClass.InnerClass i = p.new InnerClass(); an instance of an inner class cannot be created without an instance of its outer class instances of an inner class always have a (hidden) reference to an instance of its outer class 37

Inner classes in inner classes from an inner class, an outer class on any level of nesting can be accessed class A { private void f() { class B { private void g() { class C { void h() { g(); f(); public class X { public static void main(string[] args) { A a = new A(); A.B b = a.new B(); A.B.C c = b.new C(); c.h(); 38

Inheriting from inner classes a reference to an instance of the outer class has to be explicitly passed class WithInner { class Inner { class InheritInner extends WithInner.Inner { InheritInner(WithInner wi) { wi.super(); // InheritInner() { // compile-time error public static void main(string[] argv) { WithInner wi = new WithInner(); InheritInner ii = new InheritInner(wi); 39

Static inner classes do not have a reference to an instance of its outer class can have static elements non-static inner class cannot have static elements do not need an instance of the outer class they do not have the reference to it in fact, they are normal classes just placed in the namespace of the outer class public class MyClass { public static class InnerClass { public static void main(string[] args) { MyClass.InnerClass ic = new MyClass.InnerClass(); 40

Static inner classes can be defined in an interface non-static ones cannot be interface MyInterface { static class Inner { int a, b; public Inner() { void m(); 41

Inner classes and.class files inner class own.class file OuterName$InnerName.class MyClass$InnerClass.class anonymous inner classes OuterName$SequentialNumber.class MyClass$1.class static inner class can have the main method launching: java JmenoVnejsi$JmenoVnitrni 42

Reasons for using inner classes hiding an implementation access to all elements of the outer class callbacks... 43

Java, winter Slides semester version 2014 J03.en.2014.01 This slides are licensed under a Creative Commons Attribution-NonCommercial 4.0 International License. 44