Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html.

Slides:



Advertisements
Similar presentations
Yoshi
Advertisements

Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
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.
1 Why do we need exceptions? In C, return variables must be used to indicate errors: if((fd = fopen(path,...)) == -1){ if(errno==a){...} else if(errno==b){...}
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
1 Exception Handling (in a nutshell). 2 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
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.
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.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
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.
Slides Credit Umair Javed LUMS Web Application Development.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Exception. Runtime Error Consider the following program: public class BadArray { public static void main(String[] args) { // Create an array with three.
COMP Exception Handling Yi Hong June 10, 2015.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
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.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
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.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
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 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.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
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.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Object Throwable ErrorException RuntimeException.
Java Exceptions a quick review….
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Chapter 12 Exception Handling
Chapter 13 Exception Handling
Lecture 11 Objectives Learn what an exception is.
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.
Chapter 12 Exception Handling and Text IO Part 1
Java Basics Exception Handling.
Exception Handling and Event Handling
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:

Throw Statements Before you can catch an exception, some code somewhere must throw one. Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java runtime environment. Regardless of what throws the exception, it's always thrown with the throw statement. Reference:

Exceptions As you have probably noticed, the Java platform provides numerous exception classes. All the classes are descendants of the Throwable class, and all allow programs to differentiate among the various types of exceptions that can occur during the execution of a program. You can also create your own exception classes to represent problems that can occur within the classes you write. In fact, if you are a package developer, you might have to create your own set of exception classes to allow users to differentiate an error that can occur in your package from errors that occur in the Java platform or other packages. Reference:

Throw Statement All methods use the throw statement to throw an exception. The throw statement requires a single argument: a Throwable object. Throwable objects are instances of any subclass of the Throwable class. Syntax: throw someThrowableObject;

Throw Statement Example private static int sample(int input){ if(input == 0) // Immediately throws exception if 0 throw new ArithmeticException(); return 5 / input; }

Exception Hierarchy

Exceptions vs. Errors Error Class When a dynamic linking failure or other hard failure in the Java virtual machine occurs, the virtual machine throws an Error. Exception Class Most programs throw and catch objects that derive from the Exception class. An Exception indicates that a problem occurred, but it is not a serious system problem. Most programs you write will throw and catch Exceptions as opposed to Errors.

Try-Catch Statements Valid Java programming language code must honor the Catch or Specify Requirement. This means that code that might throw certain exceptions must be enclosed by either of the following: A try statement that catches the appropriate exception A method that specifies that it can throw a particular type of exception

Try-Catch Statements Syntax) try{ // Code that may throw an exception } catch(SomeException e){ System.out.println(“ExceptionType: “ + e.getMessage()); } ** catch is only executed if the specific exception occurs

Try-Catch Statements try{ // Code that may throw an exception } catch(SomeException e){ System.out.println(“ExceptionType: “ + e.getMessage()); } finally{ // Ending statements } ** finally is ALWAYS executed

Throws Statement Sometimes it may be a better choice to notify other methods that an exception may occur rather than handling the method with a try-catch A throws statement is used to show what type of an exception a method may throw First, look at the method below: public int divide(int a, int b){ return a/b; }

Throws Statement The method below will throw an ArithmeticException when b is equal to 0 The divide method can notify its callers that an ArithmeticException could be thrown by adding the throws statement below public int divide(int a, int b) throws ArithmeticException{ return a/b; }

Handling Known Exceptions Although it is not required, the caller of this method can use a try-catch to elegantly handle an ArithmeticException if it occurs public static void main(String[] args) { try { System.out.println(divide(3, 0)); } catch (ArithmeticException e) { System.out.println("Arithmetic Exception: " + e.getMessage()); System.out.println("Second parameter cannot be 0"); } public static int divide(int a, int b) throws ArithmeticException{ return a/b; }

Common Exceptions The Exceptions below are testable on the AP Computer Science A Exam 1.ArithmeticException – Dividing by 0 2.NullPointerException – Sending a message to a null variable 3.IndexOutOfBoundsException – Trying to access index 10 of a list that has 4 elements 4.ArrayIndexOutOfBoundsException – Trying to access index 11 of 5 element array 5.IllegalArgumentException – occurs when a method is passed an illegal argument

Checked vs. Unchecked Exceptions Checked Exceptions are exceptions that are subclasses of Exception and not the subclass of RuntimeException Unchecked Exceptions are exceptions that are subclasses of RuntimeException Java requires all checked exceptions to be “handled” (caught or specified) Java does not require unchecked exceptions to be handled by the programmer Example) Thread.sleep(1000); //Throws InterruptedException **InterruptedException is a direct subclass of Exception and is therefore a checked Exception. The line above must be placed in a try- catch or a throws statement must be added to the method

Summary Use the throw statement to force an exception to occur Example) throw new ArithmeticException(); If it is known that an error may occur, you must catch or specify Catch an Exception with a try-catch statement try{ } catch(Exception e){ } Specify that an Exception occurs by adding a throws statement next to the method header Example) public int mystery(int a, int b) throws ArithmeticException{

Types of Errors Review Logic – An error that occurs when the program runs but unexpected results are produced Syntax – An error in spelling, punctuation, or placement of certain key symbols in a program Runtime – An error detected after compilation – results in an error message being produced rather than the expected output