Software Practice 1 - Error Handling

Similar documents
Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Here is a hierarchy of classes to deal with Input and Output streams.

6.Introducing Classes 9. Exceptions

2- Runtime exception: UnChecked (execution of program) automatically propagated in java. don t have to throw, you can but isn t necessary

Date: AIM. Write a Java program to demo simple inheritance PROCEDURE

Unit 5 - Exception Handling & Multithreaded

BBM 102 Introduction to Programming II Spring Exceptions

BBM 102 Introduction to Programming II Spring 2017

More on Exception Handling

More on Exception Handling

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

Exceptions - Example. Exceptions - Example

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Software Practice 1 Basic Grammar

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

By: Abhishek Khare (SVIM - INDORE M.P)

ITI Introduction to Computing II

ITI Introduction to Computing II

CS1020 Data Structures and Algorithms I Lecture Note #8. Exceptions Handling exceptional events

ECE 122. Engineering Problem Solving with Java

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

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

EXCEPTION HANDLING. Summer 2018

Sri Vidya College of Engineering & Technology Question Bank

Programming II (CS300)

Exceptions and Libraries

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

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Chapter 14. Exception Handling and Event Handling ISBN

What are Exceptions?

16-Dec-10. Consider the following method:

Exception Handling CSCI 201 Principles of Software Development

Exceptions. CSC207 Winter 2017

Software Practice 1 - Multithreading

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige


Datta Meghe College of Engineering Department of Electronics Engineering Subject: Object Oriented Programming Methodology

Data Structures. 02 Exception Handling

Software Practice 1 - File I/O

Chapter 12 Exception Handling

Exception-Handling Overview

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

Introductory Programming Exceptions and I/O: sections

School of Informatics, University of Edinburgh

Chapter 13 Exception Handling

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

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

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Chapter 11. Outline. Example: The Quotient app What Are Exceptions? Java By Abstraction Chapter 11

Introduction to Software Design

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

CSCI 261 Computer Science II

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

Programming II (CS300)

Java Errors and Exceptions. Because Murphy s Law never fails

17. Handling Runtime Problems

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

CSC 1214: Object-Oriented Programming

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

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

File I/O and Exceptions

C16b: Exception Handling

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

Exception Handling. --After creating exception object,method handover that object to the JVM.

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

Java Programming. Lab Manual

Lecture 19 Programming Exceptions CSE11 Fall 2013

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Fundamentals of Object Oriented Programming

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

Exception in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

Exception Handling. Exception Handling

Object Oriented Programming

Exception Handling in Java

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

CS159. Nathan Sprague

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

Exceptions Handling Errors using Exceptions

CSE 413 Winter 2001 Midterm Exam

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

Full file at Chapter 2 - Inheritance and Exception Handling

Introduction to Computer Science II CS S-22 Exceptions

G.PULLAIAH COLLEGE OF ENGINEERING AND TECHNOLOGY

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

EXCEPTIONS. Java Programming

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

What can go wrong in a Java program while running?

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

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

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

COS226 - Spring 2018 Class Meeting # 21 April 23, 2018

CS159. Nathan Sprague

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

Transcription:

Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5 Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim (42) T.A. Sujin Oh Junseong Lee 1 (43)

2 Exception An exception (or exceptional event) is a problem that arises during the execution of a program When an Exception occurs the normal flow of the program is disrupted and the program/application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled

3 Exception occurring scenarios $Enter a integer number : 4.05 // A user has entered an invalid data open( 404_file, w ) // A file needs to be opened cannot be found listen(channel_b) // channel_b is disconnected

Exception Three Categories Checked exceptions Compile time exceptions Programmer should take care of (handle) these exceptions Unchecked exceptions Runtime exceptions Including programming bugs, logic errors or improper use of an API Errors These are not exception at all, but problems arise beyond the control of the user and programmer e.g. OutofMemoryError, ThreadDeath 4

5 Checked Exceptions If you use FileReader class to read data from a file, if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception. import java.io.file; import java.io.filereader; public class FilenotFound_Demo { public static void main(string args[]) { File file = new File("E://file.txt"); FileReader fr = new FileReader(file); C:\>javac FilenotFound_Demo.java FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown FileReader fr = new FileReader(file); ^ 1 error

6 Unchecked Exceptions If you have declared an array of size and trying to call the 6 th element of the array then an ArrayIndexOutOfBoundsException exception occurs. public class Unchecked_Demo { public static void main(string args[]) { int num[] = {1, 2, 3, 4; System.out.println(num[5]); Exception in thread "main" java.lang.arrayindexoutofboundsexception: 5 at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

7 Exception Hierarchy Following is a list of most common checked and unchecked Java's Built-in Exceptions.

Exception Hierarchy Object Throwable Exceptions Checked Exceptions ClassNotFoundException CloneNotSupportedException InstantiationException IOException Errors RuntimeExceptions Unchecked Exceptions ArithmeticException IllegalArgumentException Following is a list of most common checked and unchecked Java's Built-in Exceptions. IndexOutOfBoundsException 8

9 Exception Methods Sr.No. 1 2 3 4 5 6 Method & Description public String getmessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. public Throwable getcause() Returns the cause of the exception as represented by a Throwable object. public String tostring() Returns the name of the class concatenated with the result of getmessage(). public void printstacktrace() Prints the result of tostring() along with the stack trace to System.err, the error output stream. public StackTraceElement [] getstacktrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. public Throwable fillinstacktrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

10 Catching Exceptions A method catches an exception using a combination of the try and catch keywords A try/catch block is placed around the code that might generate an exception try { // Protected code catch(exceptionname e1) { // Catch block

11 try-catch Example // File Name : ExcepTest.java import java.io.*; public class ExcepTest { public static void main(string args[]) { try { int a[] = new int[2]; System.out.println("Access element three :" + a[3]); catch(arrayindexoutofboundsexception e) { System.out.println("Exception thrown :" + e); System.out.println("Out of the block");

12 Multiple Catch Blocks try { // Protected code catch(exceptiontype1 e1) { // Catch block catch(exceptiontype2 e2) { // Catch block catch(exceptiontype3 e3) { // Catch block

13 The Finally Block The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. try { // Protected code catch(exceptiontype1 e1) { // Catch block catch(exceptiontype2 e2) { // Catch block catch(exceptiontype3 e3) { // Catch block finally { //The finally block always executes.

14 The Finally Block Example public class ExcepTest { public static void main(string args[]) { int a[] = new int[2]; try { System.out.println("Access element three :" + a[3]); catch(arrayindexoutofboundsexception e) { System.out.println("Exception thrown :" + e); finally { a[0] = 6; System.out.println("First element value: " + a[0]); System.out.println("The finally statement is executed");

15 Notes A catch clause cannot exist without a try statement. It is not compulsory to have finally clauses whenever a try/catch block is present. The try block cannot be present without either catch clause or finally clause. Any code cannot be present in between the try, catch, finally blocks.

16 The Throws/Throw Keyword If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. import java.io.*; public class classname { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); // Remainder of class definition

17 The try-with-resources Generally, when we use any resources like streams, connections, etc. we have to close them explicitly using finally block. In the following program, we are reading data from a file using FileReader and we are closing it using finally block. try(filereader fr = new FileReader("file path")) { // use the resource catch() { // body of catch

18 Example import java.io.filereader; import java.io.ioexception; public class Try_withDemo { public static void main(string args[]) { try(filereader fr = new FileReader("E://file.txt")) { char [] a = new char[50]; fr.read(a); // reads the contentto the array for(char c : a) //prints the characters one by one System.out.print(c); catch(ioexception e) { e.printstacktrace();

19 Notes To use a class with try-with-resources statement it should implement AutoCloseable interface and the close() method of it gets invoked automatically at runtime. You can declare more than one class in try-with-resources statement. While you declare multiple classes in the try block of try-withresources statement these classes are closed in reverse order. Except the declaration of resources within the parenthesis everything is the same as normal try/catch block of a try block. The resource declared in try gets instantiated just before the start of the try-block. The resource declared at the try block is implicitly declared as final.

20 User-defined Exception All exceptions must be a child of Throwable. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class. class MyException extends Exception {

21 Example // File Name InsufficientFundsException.java import java.io.*; public class InsufficientFundsException extends Exception { private double amount; public InsufficientFundsException(double amount) { this.amount = amount; public double getamount() { return amount;

22 Example (cont d) // File Name CheckingAccount.java import java.io.*; public class CheckingAccount { private double balance; private int number; public CheckingAccount(int number) { this.number = number; public void deposit(double amount) { balance += amount; public void withdraw(double amount) throws InsufficientFundsException { if(amount <= balance) { balance -= amount; else { double needs = amount - balance; throw new InsufficientFundsException(needs); public double getbalance() { return balance; public int getnumber() { return number;

23 Example (cont d) // File Name BankDemo.java public class BankDemo { public static void main(string [] args) { CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500..."); c.deposit(500.00); try { System.out.println("Withdrawing $100..."); c.withdraw(100.00); System.out.println("Withdrawing $600..."); c.withdraw(600.00); catch(insufficientfundsexception e) { System.out.println("Sorry, but you are short $" + e.getamount()); e.printstacktrace();

24 [Lab Practice #5] Implement SimpleCalculator.java When methods try to illegal action Throw exception (define exception when it doesn t exist) After throw exception, process should be aborted Exceptions OutOfRangeException // Range of result (0 ~ 9999) AddZeroException // add() is not allowed to add zero SubtractZeroException // subtract() is not allowed to subtract zero

25 [Lab Practice #5] class SimpleCalculator Field result // integer number (0~9999) Methods : add(int value1, int value2) subtract(int value1, int value2) print() // print result reset() // reset result as 0

26 [Lab Practice #5] Exceptions Field String message Methods/constructor Exceptions() Exceptions(String message) getmessage()

27 [Lab Practice #5] File week06.java can has only week06 class Functions in week06.java can NOT have any throws keyword If method throw exception in scenario, handle the exception with try-catch Print which exception is thrown Hint : use a message in exception Print result of each scenario

28 [Lab Practice #5] Addition example

29 [Lab Practice #5] Subtract example

30 [Lab Practice #5] Other example

[Submit] Upload to i-campus Compress your SimpleCalculator.java & week06.java file to zip file Do not use any package keyword File name: studentid_lab04.zip Due date Today 23:59:59 Class 42 (04/09 Monday) Class 43 (04/11 Wednesday) Penalty: -10% of each lab score per one day 31