Exceptions: When things go wrong

Slides:



Advertisements
Similar presentations
Recitation 4. 2-D arrays. Exceptions. Animal[] v= new Animal[3]; 2 declaration of array v v null Create array of 3 elements a6 Animal[] null Assign.
Advertisements

Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
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.
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.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
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.
Object Oriented Programming with Java (150704).  Throwable Exception (This class will catch exceptions generated by prog.) (Create your own custom exception.
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.
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.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
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.
Recitation 3 2D Arrays, Exceptions. 2D arrays 2D Arrays Many applications have multidimensional structures: ●Matrix operations ●Collection of lists ●Board.
Chapter 8-Exception Handling/ Robust Programming.
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.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
CSE 1201 Object Oriented Programming
Chapter 14 – Exception Handling
Generics, Exceptions and Undo Command
Exceptions In this lecture:
Recitation 2 Exception handling.
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Exceptions, Interfaces & Generics
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
Introduction to OO Program Design
COMPSCI 230 S Programming Techniques
Multithreading in Java
Exceptions 10-Nov-18.
Handling Exceptions.
Advanced Programming Behnam Hatami Fall 2017.
Exception Handling Chapter 9.
Exceptions & exception handling
Phil Tayco Slide version 1.0 Created Nov. 26, 2017
ATS Application Programming: Java Programming
Exceptions & exception handling
EXCEPTION HANDLING OR ERROR HANDLING.
Abdulmotaleb El Saddik University of Ottawa
Exception Handling CSCI293 - C# October 3, 2005.
Exception Handling and Reading / Writing Files
Fundamental Error Handling
Web Design & Development Lecture 7
Exception Handling in Java
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.
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 Exception Dept. Business Computing University of Winnipeg
Java Basics Exception Handling.
CMSC 202 Exceptions.
Java Programming: From Problem Analysis to Program Design, 4e
Basic Exception Handling
Presentation transcript:

Exceptions: When things go wrong Topics to be covered: What is an exception Throwing an exception Catching an exception

Expecting the unexpected When you design a program, you develop an algorithm for what’s supposed to happen; but, as we all know, life doesn’t always work that way. Example: The user enters a floating point number instead of a integer You try to evaluate X / Y, when Y has the value 0 You try to access position 10 in an array with 10 elements

Example public class Exception1 { public static void main(String [] args) { int x = 1, y = 0; int z = x/y; System.out.println("Finished!"); } Screen Output: Exception in thread “main” java.lang.ArithmeticException: / by zero at Exception1.main(Exception1.java:7)

Exceptions are objects When something goes wrong we need to do something about it Exceptions are objects that contain information about what went wrong and where it happened The getMessage() method returns a string explaining the exception Exception in thread “main” java.lang.ArithmeticException: / by zero The printStackTrace() method prints the call stack trace at Exception1.main(Exception1.java:7)

Exception class hierarchy Object Throwable Error Exception RunTimeException ArithmeticException IndexOutOfBoundsException You can define your own exceptions

Creating your own exception public class MyException extends Exception { public MyException(String message) super(message); }

Another (silly) example public class Exception2 { public static void main(String [] args) { int x = 1, y = 0; System.out.println("Starting the calculations"); int ans = calculations(x,y); System.out.println("The answer is: " + ans); } public static int calculations(int x, int y) { int ans = division(x,y); return ans; public static int division(int x, int y) { int z = x/y; return z;

Normal control flow main() calculations() division() Execution begins in main() which invokes calculations() which then invokes division(). When division() finishes control returns to calculations() and then from there to main().

When an exception is generated main() calculations() division() OH NO! When a method has a problem, it generates an exception object. It then throws the exception back along the call path. The exception travels along the call path until it is caught by a compatible catch statement. The catch statement may exist in the method where the exception was first generated or in any other method on the call path.

The throw clause A method must declare that it may throw an exception This information is as much a part of its normal header as its return type or its parameters public static int division(int x, int y) throws MyException The information lets anyone calling the method know that they must be prepared for it to throw this exception A throw statement is a little like a return statement except that a method may throw more than one exception and each exception may be of a different type

Throwing an exception public class Exception2 { public static void main(String [] args) throws MyException { int x = 1, y = 0; System.out.println("Starting the calculations"); int ans = calculations(x,y); System.out.println("The answer is: " + ans); } public static int calculations(int x, int y) throws MyException { int ans = division(x,y); return ans; public static int division(int x, int y) throws MyException { int z = 0; if(y==0) { MyException exceptionObj = new MyException("Division would be undefined"); throw exceptionObj; } else z = x/y; return z;

The screen output Starting the calculations Exception in thread "main" MyException: Division would be undefined at Exception2.division(Exception2.java:19) at Exception2.calculations(Exception2.java:12) at Exception2.main(Exception2.java:7) Press any key to continue...

Catching an exception If a throw statement is like return statement, then a try/catch statement is a little like an if/else statement. Statements that may throw an exception must be enclosed in a try block---this is just a regular block of code preceded by the key word try The try block is followed by a catch block, which gives the instructions to execute if an exception of the specified type is caught The catch clause always has a single parameter specifying the exception to be caught The catch body is executed only if an exception of the appropriate type is thrown

A try/catch example public class Exception2 { … { … public static int calculations(int x, int y) } public static int division(int x, int y) { int z = 0; try { if(y==0) { MyException eObj = new MyException("Division would be undefined"); throw eObj; } else z = x/y; catch(MyException e) { System.out.println("The exception message is: " + e.getMessage()); return z;

The screen output Starting the calculations The exception message is: Division would be undefined The answer is: 0 Press any key to continue...

Points to remember The try body contains statements that may throw an exception; at least one statement in the block must potentially throw an exception Each catch block has a parameter that defines the type of exception it can catch If a method catches an exception, it stops the propagation of that exception up the call path. Methods with appropriate try/catch blocks do not have throw declarations in their headers. public static int division(int x, int y) throws MyException NO