Intro to Exceptions (c) Eraj Basnayake

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

„Exceptions”. Exceptions Handling errors with exceptions Golden rule of programming: Errors occur in software programs. What really matters is what happens.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
Java Programming Exceptions. Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
COMP201 Java Programming Topic 7: Exceptions Reading: Chapter 11.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Advanced Java Programming – Eran Toch Methodologies in Information System Development Tutorial: Advanced Java Programming and Database connection Eran.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
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.
CS203 Java Object Oriented Programming Errors and Exception Handling.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Preventing and Correcting Errors
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
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:
Java Exceptions a quick review….
Chapter 14 – Exception Handling
Exceptions In this lecture:
Exceptions: When things go wrong
Chapter 10 – Exception Handling
Advanced Programming in Java
Tirgul 13 Exceptions 1.
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
Introduction to OO Program Design
CS102 – Exceptions David Davenport Latest: May 2015
COMPSCI 230 S Programming Techniques
Exceptions The Need for Exceptions Throwing Exceptions
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Handling Exceptions.
Advanced Programming Behnam Hatami Fall 2017.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
EE422C Software Implementation II
ATS Application Programming: Java Programming
Exceptions & Error Handling
Abdulmotaleb El Saddik University of Ottawa
OBJECT ORIENTED PROGRAMMING
Web Design & Development Lecture 7
Exception Handling in Java
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Exceptions 19-Feb-19.
Lecture 11 Objectives Learn what an exception is.
Java Exceptions Dan Fleck CS211.
Exceptions 25-Apr-19.
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.
Exceptions 22-Apr-19.
Chapter 12 Exception Handling and Text IO Part 1
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exceptions 10-May-19.
Java Basics Exception Handling.
Exception Objects An exception is an abnormal condition that arises in a code sequence at rum time. Exception is a way of signaling serious problem.
Exceptions 5-Jul-19.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Intro to Exceptions (c) Eraj Basnayake Introduction to Exceptions 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

Intro to Exceptions (c) Eraj Basnayake Exceptions are run-time events which indicate an exceptional situation Int[] t = new int[10]; for(int i=0; i<100; i++) t[i] = … ArrayIndexOutOfBoundsException String s=null; System.out.println(s.length()); NullPointerException int i=5; for(int j=3;j>=-1;j--){ System.out.println(i/j); } ArithmeticException 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

Intro to Exceptions (c) Eraj Basnayake Exception classes Object Throwable Error Exception RuntimeException Object Object Object Object Object Exceptions you have to catch (checked exceptions) Exceptions you do not need to catch (but can catch) 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

Intro to Exceptions (c) Eraj Basnayake … methodC(…){ … for(int j=3;j>=-1;j--){ System.out.println(i/j); } ArithmeticException … methodB(…){ … methodC(…) } … methodA(…){ … methodB(…) } Ignored code … main(…){ … methodA(…) } 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

Intro to Exceptions (c) Eraj Basnayake Exception Handling - I … methodC(…){ … try{ for(int j=3;j>=-1;j--){ System.out.println(i/j); } }catch(ArithmeticException ae){ System.out.println(ae); ArithmeticException Ignored code … methodB(…){ … methodC(…) } … methodA(…){ … methodB(…) } … main(…){ … methodA(…) } 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

Intro to Exceptions (c) Eraj Basnayake Exception Handling - II … methodC(…) throws ArithmeticException{ … for(int j=3;j>=-1;j--){ System.out.println(i/j); } … methodB(…) throws ArithmeticException{ … methodC(…) } … methodA(…){ … try{ methodB(…); catch(ArithmeticException ae){ System.out.println(ae); } Ignored code … main(…){ … methodA(…) } 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

Intro to Exceptions (c) Eraj Basnayake The try catch block try{ //code that may throw exception… }catch(ExceptionType1 e1){ //code to handle exceptions of type ExceptionType1 or subclass }catch(ExceptionType2 e2){ //code to handle exceptions of type ExceptionType2 or subclass … //more catch blocks if needed }finally{ //code always to be executed after try block code } Each try must have at least 1 catch A finally block (optional) is always executed regardless of what happens in the try 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

Intro to Exceptions (c) Eraj Basnayake Structuring a method … doSoemthing(…){ // code that does not throw exceptions // try-catch-finally blocks //code that does not throw exceptions //try-catch-finally blocks … } try{ //code that may throw exception… }catch(ExceptionType1 e1){ //code to handle exceptions }catch(ExceptionType2 e2){ … //more catch blocks if needed }finally{ //code always to be executed} 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

Intro to Exceptions (c) Eraj Basnayake Example public class Foo{ public static int divide (int[] array, int index){ try{ System.out.println(“Try block”); array[index + 2] = array[index]/array[index+1]; System.out.println(“Done try”); }catch(ArithmeticException ae){ System.out.println(“Arithmetic exception”); }catch(ArrayIndexOutOfBoundsException aioobe){ System.out.println(“Index out of bounds”); }finally{ System.out.println(“finally”); } System.out.println(“Code outside of try”); public static void main(String[] args){ … 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

Intro to Exceptions (c) Eraj Basnayake Writing your own public class ZeroDivideException extends Exception{ private int index; public ZeroDivideException(){ index = -1;} public ZeroDivideException(int index){ super(“/ by zero”); this.index = index; } public int getIndex(){ return index; 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

this exception, fix it by setting array value to 1 and recalling Throwing your own public static int divide (int[] array, int index) throws ZeroDivideException { try{ System.out.println(“Try block”); array[index + 2] = array[index]/array[index+1]; System.out.println(“Done try”); }catch(ArithmeticException ae){ System.out.println(“Arithmetic exception”); throw new ZeroDivideException(index+1); }catch(ArrayIndexOutOfBoundsException aioobe){ System.out.println(“Index out of bounds”); }finally{ System.out.println(“finally”); } System.out.println(“Code outside of try”); Write a main() to catch this exception, fix it by setting array value to 1 and recalling method for next index. 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

Exceptions: Why do we need it ADVANTAGES: 1. Separating Error Handling Code from "Regular" Code Suppose you need to read an entire file in memory: readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } BUT: What happens if the file can't be opened? What happens if the length of the file can't be determined? What happens if enough memory can't be allocated? What happens if the read fails? What happens if the file can't be closed? 2/24/2019 From: java.sun.com

Exceptions: Why do we need it One way to do it. errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } else { errorCode = -5; } return errorCode; “Spaghetti code”. Not good. 2/24/2019 From: java.sun.com

Exceptions: Why do we need it BETTER WAY readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { } catch (memoryAllocationFailed) { } catch (readFailed) { } catch (fileCloseFailed) { } 2/24/2019 From: java.sun.com

Exceptions: Why do we need it ADVANTAGES: 2: Propagating Errors Up the Call Stack method1 { try { call method2; } catch (exception) { doErrorProcessing; } method2 throws exception { call method3; method3 throws exception { call readFile; What’s good about that ? Only method 1 has to deal with errors. Only method1 decides what do if an error occurs. Consider the alternative: Each method will have to deal with errors. Do you always know ahead of time what to do with errors? 2/24/2019 From: java.sun.com

Exceptions: Why do we need it ADVANTAGES: 3: Grouping Error Types, Error Differentiation. What’s good about that ? Gives you a lot of flexibility in error handling: you can either do it in a very general fashion, or in a very exact (error-specific) fashion. 2/24/2019 From: java.sun.com

Intro to Exceptions (c) Eraj Basnayake Exception potpourri Accessing the message in the exception: getMessage() Accessing a stack trace: printStackTrace() public class String … public String concat(String str) Concatenates the specified string to the end of this string. … Throws: NullPointerException - if str is null. 2/24/2019 Intro to Exceptions (c) Eraj Basnayake

Intro to Exceptions (c) Eraj Basnayake Exception Designing them in Method design - design by contract Assert pre-condition and throw exception if pre-condition is not met Try to reuse existing exceptions whenever possible If a line could throw an exception you can + catch and fix it within the method + throw it back to be dealt with by the caller. Javadoc: /** * method description/purpose/pre-condition * @param <parameter list and description> * @return <return value and description> * @exception <Exception1 if precondition1 is not met> * @exception <Exception2 if precondition2 is not met> * … */ … someMethod(…) throws Exception1, Exception2, … { … } 2/24/2019 Intro to Exceptions (c) Eraj Basnayake