Advanced Programming in Java

Slides:



Advertisements
Similar presentations
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Advertisements

Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Index Exception handling Exception In Java Exception Types
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
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.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
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.
Peyman Dodangeh Sharif University of Technology Spring 2015.
Peyman Dodangeh Sharif University of Technology Fall 2013.
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 }
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
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.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
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.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Advanced Programming in Java
Exceptions In this lecture:
Chapter 10 – Exception Handling
Tirgul 13 Exceptions 1.
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Exceptions, Interfaces & Generics
Introduction Exception handling Exception Handles errors
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.
ATS Application Programming: Java Programming
Chapter 12 Exception Handling
OBJECT ORIENTED PROGRAMMING
Exception Handling Chapter 9 Edited by JJ.
Web Design & Development Lecture 7
Java Exception Very slightly modified from K.P. Chow
Exception Handling in Java
Java Exception Very slightly modified from K.P. Chow
Managing Errors and Exceptions
Lecture 11 Objectives Learn what an exception is.
Java Exceptions Dan Fleck CS211.
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.
Tutorial Exceptions Handling.
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.
Tutorial MutliThreading.
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.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Exceptions and Exception Handling
Presentation transcript:

Advanced Programming in Java Exception Mehdi Einali

Agenda Error handling mechanisms Exception handling framework Benefits of exception handling framework Exception handling in Java

Error handling mechanisms

Watch This Method public static Integer getYear(String day){ String yearString = day.substring(0,4); int year = Integer.parseInt(yearString); return year; } public static void main(String[] args) { String day = "2010/11/29"; Integer year = getYear(day); System.out.println(year);

Exceptions What is wrong with it? What if day parameter is not a day representation? day = “salam!” What if day parameter is malformed? Day = “29 Nov 2010” What if day parameter is empty? String s = ""; What if day parameter is null? These occasions are called Exception

Handling Exceptions What to do with exceptions? Exit the program Printing the error on console Returning a special value e.g. -1

Important Note Sometimes the method can’t handle the exception effectively What should a method do when an exception occurs? Exit the program? Suppose you are in a desktop application Excel, Word, a game, … Print on console? edu site A game

Returning a Special Value We can return a special value to report an exception E.g. return null; return -1; return 0; return “”; Why not?

Why not? There is no special value There are many exceptions Ambiguity Need for documentation Combination of program code and exception code

Exception handling framwork

Exception as object Exceptional event Error that occurs during runtime Cause normal program flow to be disrupted Examples ? Divide by zero errors Accessing the elements of an array beyond its range Invalid input Hard disk crash Opening a non-existent file Heap memory exhausted

Default Exception Handling Provided by Java runtime Prints out exception description Prints the stack trace Hierarchy of methods where the exception occurred Causes the program to terminate

example 17 class DivByZero { 18 public static void main(String a[]) { 19 System.out.println(3/0); 20 } 21 } Exception in thread "main" java.lang.ArithmeticException: / by zero at exception.Test2.main(Test2.java:19) Note: Exception is a runtime concept This code has no syntax error (No compile-time error)

What Happens When an Exception Occurs? When an exception occurs within a method The method creates an exception object And hands it off to the runtime system This job is called “throwing an exception” Exception object contains information about the error its type the state of the program when the error occurred Exception line of code

What Happens When an Exception Occurs (2)? The runtime system searches the call stack for a method that contains an exception handler When an appropriate handler is found The runtime system passes the exception to the handler The exception handler catches the exception What if the runtime system can not find an exception handler? Uses the default exception handler

Exception Handling in Java public static Integer getYear(String day) { String yearString = day.substring(0, 4); int year = Integer.parseInt(yearString); return year; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a well-formed date: "); String date = scanner.next(); Integer year = getYear(date); System.out.println(year);

public static Integer getYear(String day) throws Exception { if (day == null) throw new Exception("null value"); if (day.length() == 0) throw new Exception("empty value"); if (!matchesDateFormat(day)) throw new Exception("malformed value"); String yearString = day.substring(0, 4); int year = Integer.parseInt(yearString); return year; } private static boolean matchesDateFormat(String input) { return input.matches("\\d\\d\\d\\d/\\d\\d/\\d\\d");

main() public static void main(String[] args) { Scanner scanner = new Scanner(System.in); boolean ok = false; while (ok == false) { System.out.print("Enter a well-formed date: "); String date = scanner.next(); try { Integer year = getYear(date); System.out.println(year); ok = true; } catch (Exception e) { System.out.println(e.getMessage()); }

Exception Handling Keywords throw throws a new exception throws Declares exception throw If a method may throw an exception, it should declare it try Start a block with exception handling catch Catch the exception

syntax

Advantages of exception handling framework

Benefits of Exception Handling Framework Separating Error-Handling code from “regular” business logic code Propagating errors up the call stack Grouping and differentiating error types

Separating Error-Handling Code Consider pseudocode method It reads an entire file into memory readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; }

Without exception handling framework

With exception handling framework Common Logic Exceptions

Note You should still write code for detecting, reporting and handling exceptions Exception handling framework is not responsible for these jobs! It only helps you organize the work more effectively

Propagating Errors Up the Call Stack method1 is the only method interested in the errors that might occur within readFile

Old approach ____ method2 and method3 to propagate the error codes

With framework

Propagating Errors Up the Call Stack Traditional approach Each method should explicitly forward the exception Use a special return code Using return type for reporting exceptions Smells bad! New approach Automatic Beautiful!

Grouping and Differentiating Error Types All exceptions thrown within a program are objects The grouping or categorizing of exceptions is a natural outcome of the class hierarchy

Catching exception

Example class MultipleCatch { public static void main(String args[]) { try { int den = Integer.parseInt(args[0]); System.out.println(3/den); } catch (ArithmeticException exc) { System.out.println(“Divisor was 0.”); } catch (ArrayIndexOutOfBoundsException exc2) { System.out.println(“Missing argument.”); } System.out.println(“After exception.”);

Nested Tries class NestedTryDemo { public static void main(String args[]){ try { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); System.out.println(a/b); } catch (ArithmeticException e) { System.out.println(“Div by zero error!"); } } catch (ArrayIndexOutOfBoundsException) { System.out.println(“Need 2 parameters!");

Accessing the Stack Trace e.printStackTrace(); e.getStackTrace(); for(StackTraceElement methodCall : e.getStackTrace()){ System.out.println(methodCall); }

Multiple Catch Blocks When providing multiple catch handlers: handle specific exceptions before handling general exceptions. Multi-Catch Blocks (Java7): catch(IOException | IllegalStateException multie) {…}

Try-with resource Try-with-Resources (Java7) java.lang.AutoCloseable interface

autocloseable

finally

syntax Contains the code for cleaning up after a try or a catch try { //.. } catch (ExceptionType e) { //… } ... } finally { <code to be executed before the try block ends> } Contains the code for cleaning up after a try or a catch

Finally Block of code is always executed Despite of different scenarios: Normal completion Forced exit occurs using a return, a continue or a break statement Caught exception thrown Exception was thrown and caught in the method Uncaught exception thrown Exception thrown was not specified in any catch block in the method

1 finnally 3 catch 4 2

Write your own exception

Writing Your Own Exceptions Your class should extend Exception class Exception subclasses could be thrown and caught Steps to follow Create a class that extends Exception class Customize the class Members and constructors may be added to the class Exception classes are usually simple classes With no (or few) methods and properties

Example class HateStringExp extends Exception { /* some code */ } String input = "invalid input"; try { if (input.equals("invalid input")) { throw new HateStringExp(); System.out.println("Accept string."); } catch (HateStringExp e) { System.out.println("Hate string!”);

getYear(), revisited public static Integer getYear(String day) throws Exception { if (day == null) throw new NullPointerException(); if (day.length() == 0) throw new EmptyValueException(); if (!matchesDateFormat(day)) throw new MalformedValueException(); String yearString = day.substring(0, 4); int year = Integer.parseInt(yearString); return year; } private static boolean matchesDateFormat(String input) { return input.matches("\\d\\d\\d\\d/\\d\\d/\\d\\d");

Checked/unchecked exception

Exception types Checked exception Unchecked exception Compiler obligation Make your choice Handle it or throw it Unchecked exception No compiler obligation Runtime risky Do on your own risk Based on Exception severity

Unchecked Exceptions private static void function(String[] args) { int den = Integer.parseInt(args[0]); System.out.println(3 / den); } public static void main(String[] args) { function(args); The method function() may throw exceptions But it has not declared it with throws keyword Why? Because some exceptions are unchecked such as ArithmeticException and ArrayIndexOutOfBoundsException

Checked and Unchecked Exceptions Java compiler checks the program should catch or list the occurring exception If not, compiler error will occur Unchecked exceptions Not subject to compile-time checking for exception handling Built-in unchecked exception classes Error RuntimeException Their subclasses Unchecked exceptions only relax compiler The runtime behavior is the same

Exception Classes and Hierarchy Multiple catches should be ordered from subclass to superclass Or else, Compile error: Unreachable catch block… class MultipleCatchError { public static void main(String args[]){ try { int a = Integer.parseInt(args [0]); int b = Integer.parseInt(args [1]); System.out.println(a/b); } catch (ArrayIndexOutOfBoundsException e) { //.. } catch (Exception ex) { }

Exception and liskov principle

Exceptions & Inheritance Suppose method f() overrides parent’s method f() in child class can not throw more exceptions than those of f() in Parent class Less or equal exceptions in throws declaration These mistakes bring compiler error Why? Polymorphic method invocations may cause failure in catching some exceptions

Example (1) class Parent{ void f(){} } class Child extends Parent{ void f()throws Exception{} Result? Compiler Error

Example (2) class Parent{ void f()throws ArithmeticException{} } class Child extends Parent{ void f()throws ArithmeticException, IOException{} Result? Compiler Error

Example (3) class Parent{ void f()throws ArithmeticException{} } class Child extends Parent{ void f()throws Exception{} Result? Compiler Error

Example (4) class Parent{ void f()throws Exception{} } class Child extends Parent{ void f()throws ArithmeticException{} Result? No Error

Conclusion f() in child class can not throw more exceptions Less or equal exceptions in throws declaration f() in child class can not throw more general exceptions f() in child class can throw more specific exceptions Reason: Prevent uncaught exceptions in polymorphic invocations

Quiz! public static int myMethod(int n) { try { switch (n) { case 1: System.out.println("One"); return 1; case 2: System.out.println("Two"); throwMyException(); case 3: System.out.println("Three"); } return 4; } catch (Exception e) { System.out.println("catch"); return 5; } finally { System.out.println("finally"); return 6; class MyException extends Exception {} Quiz! private static void throwMyException() throws MyException { throw new MyException(); } int a = myMethod(1); System.out.println("myMethod(1)=" + a); a = myMethod(2); System.out.println("myMethod(2)=" + a); a = myMethod(3); System.out.println("myMethod(3)=" + a);

Result: One finally myMethod(1)=6 Two catch myMethod(2)=6 Three

end