Obravnava izjem (exception handling).

Slides:



Advertisements
Similar presentations
Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,
Advertisements

Exception Handling – illustrated by Java mMIC-SFT November 2003 Anders P. Ravn Aalborg University.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exception Handling By: Thomas Fasciano. What is an Exception?  An error condition that occurs during the execution of a Java Program.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining 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.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
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.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
Exceptions and Exception Handling (continued) Carl Alphonce CSE116.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Java Computer Industry Lab. 1 Programming Java Exception Handling Incheon Paik.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Exception Handling Exceptions and language features to handle them.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Program Errors Syntax errors Logic errors
OBJECT ORIENTED PROGRAMMING B.TECH II YR II SEMESTER(TERM 08-09) UNIT 5 PPT SLIDES TEXT BOOKS: 1. Java: the complete reference, 7th edition, Herbert schildt,
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Programming in C++ 1. Learning Outcome At the end of this slide, student able to:  Identify the different types of error in your program  Understand.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
Lecture 2 Exception handling Advanced Java Programming 1 dr inż. Wojciech Bieniecki
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Peter Andreae Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 Implementing.
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.
Uvod v C# Drugi del. Dedovanje Sintaksa Prirejanje in preverjanje tipov.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
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.
ExceptionstMyn1 Exceptions You need to understand classes and inheritance before you can understand what an exception is and appreciate what happens when.
SREČNO NOVO LETO 2009 Lara Koren, 2.c.
Srečko Bončina Izposoja e-knjig eBooks na EBSCOHost-u
Introduction Exception handling Exception Handles errors
Programming I Packets and JAR 11th lecture.
CS Week 10 Jim Williams, PhD.
Java Hello world !.
Uvod v Python
R V P 2 Predavanje 04 Animacija RVP2 Animacija.
Exceptions "A slipping gear could let your M203 grenade launcher fire when you least expect it. That would make you quite unpopular in what's left of your.
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.
Fotografiranje hrane Predmet: Tipografija in reprodukcija.
MS Excel, Open Office Calc, Gnumeric …
Obravnava izjem (exception handling).
ATS Application Programming: Java Programming
Šalej Mirko Iskraemeco, d.d. Kranj
Referat za NIT Anže Povhe, 4.b
Binarna logistična regresija
Why are we for PEACE? Zakaj smo za mir.
EXCEPTION HANDLING OR ERROR HANDLING.
Ugani število Napišimo program, ki si “izmisli” naključno število, potem pa nas v zanki sprašuje, katero je izmišljeno število. Če število uganemo, nas.
E-mobilnost in njena integracija v elektroenergetski sistem
OBJECT ORIENTED PROGRAMMING
Exceptions Complicate Code
Exceptions Complicate Code
TRY CATCH BLOCK By Kosala Rajapaksha.
Exception Handling in Java
Web Design & Development Lecture 7
Managing Errors and Exceptions
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.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
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 Exception Dept. Business Computing University of Winnipeg
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.
Presentation transcript:

Obravnava izjem (exception handling)

Ko umre programer

Uvod Ne glede na to, kako dobro smo načrtovali nek program, je še vedno možnost, da lahko med izvajanjem pride do kakšnih napak. Dobro načrtovan program mora vsebovati kodo za obravnavo napak in drugih izjemnih pogojev. Ogledali si bomo možnost obravnave izjem, ki jo nudi Java. Ta tvori objekt Exception, kadarkoli sreča nepričakovano napačno situacijo,kot na primer: neobstoječ sistemski vir, ne-numerični znak v številskem polju, primer: Integer.parseInt(br.readLine()); manjkajočo datoteko ipd.,

Kaj je izjema Izjema je nepričakovan dogodek (event), do katerega pride med izvajanjem programa in ki prekine normalen potek programskih ukazov . Primeri: Poskus dostopa do elementa izven meja nekega polja , Poskus delitve z vrednostjo 0, Poskus dostopa do nekega URL z napačnim protokolom . class test {     public static void main(String argv[ ]) {         int a=4;         int b=0;         System.out.println(a/b); // med izvajanjem dobimo ArithmeticException }

Razlika med napako in izjemo Naša koda lahko obravnava izjemo in program nadaljuje. Če pride do napake, mora program prekiniti izvajanje.

Primer Psevdo koda funkcije, ki bere datoteko: readFirstLine { open the file; // odpiranje lahko ne uspe read the first line; // branje lahko ne uspe close the file; // zapiranje lahko ne uspe }

Tradicionalna obravnava napak Javanska obravnava izjem readFirstLine { int errcode = 0; open the file; if (openError) { errcode = OPEN_ERR; } else { read the first line; if (readError) { errcode = READ_ERR; close the file; if (closeError) { errcode = errcode and CLOSE_ERROR; return errcode; } try { catch (openError) { handle error; catch (readError) { catch (closeError) {

Prednosti izjem v Javi (1) Ločena koda za obravnavo napak Pri tradicionalnem programiranju povzroča obravnavanje napak to, da je programska koda nejasna. Java loči podrobnosti obravnave nepričakovanih napak od glavne kode programa. Dobimo kodo, ki je jasna in je tako tudi možnost napak manjša .

Prednosti izjem v Javi (2) Posredovanje napak na klicni sklad Tradicionalna obravnava Java exceptions napak Metoda1 //handle ex Metoda1 //handle error Error code metoda2 metoda2 Exception ex Error code metoda3 metoda3 Error code metoda4 metoda4 Vsaka metoda išče napake in vrača kodo napake kličočo metodi. metoda4 sproži izjemo (exception); metoda1 jo ulovi.

Prednosti izjem v Javi (3) Izjeme lahko ignoriramo Tradicionalna obravnava Java exceptions napak Metoda1 //handle ex Metoda1 //handle error metoda2 metoda2 Exception ex metoda3 metoda3 Error code metoda4 metoda4 Če metoda3 ignorira napako, ne bo ta nikoli obravnavana. Izjemo lahko ulovimo in obravnavamo drugje

Kaj narediti z izjemo? Če kličemo metodo, ki lahko povzroči izjemo, imamo tri možnosti: Izjemo ulovimo in jo obravnavamo. Izjemo posredujemo naprej kličoči metodi. Izjemo ulovimo in sprožimo drugačno izjemo. To, novo izjemo bomo morali obravnavati kje drugje.

Kako ujamemo in obravnavamo izjemo? Klicana metoda bi lahko sprožila izjemo v bloku try. Vsako izjemo obravnavamo v bloku catch. Izvedemo končno obdelavo v bloku finally. try { // call the method } catch (exception1) { // handle exception1 catch (exception2) { // handle exception2 } … finally { // any final processing

Vrste izjem Exception      ClassNotFoundException      CloneNotSupportedException      IllegalAccessException      InstantiationException      InterruptedException      NoSuchFieldException      NoSuchMethodException      RuntimeException           ArithmeticException          ArrayStoreException          ClassCastException          IllegalArgumentException              IllegalThreadStateException              NumberFormatException           IllegalMonitorStateException          IllegalStateException          IndexOutOfBoundsException              ArrayIndexOutOfBoundsException             StringIndexOutOfBoundsException          NegativeArraySizeException          NullPointerException          SecurityException          UnsupportedOperationException Poznamo veliko vrst izjem, vse so izpeljane iz osnovnega razreda Exception:

Lovljenje izjem: try-catch Java omogoča, da izjeme ulovimo.  Če mislimo, da lahko v določenem delu kode pride do izjeme, jo postavimo v blok try-catch. class test {     public static void main(String argv[ ]) {         int x=6; int y=3;         try {   // Začetek bloka             for (int j=1;j<=10;j++) {                 x=x*j/y;                 y=y-1;             }             System.out.println("Rezultat je: " + y);         }         catch (Exception e) {   // Ujamemo izjemo             System.out.println("Prislo je do napake!");         }     }

Lovljenje izjem: try-catch Če poznamo tipe izjem, ki se lahko zgodijo, lahko po bloku try postavimo več catch blokov:        try {             for (int j=1;j<=10;j++) {                 x=x*j/y;                 y=y-1;             }             System.out.println("Rezultat je: " + y);         }         catch (java.lang.ArithmeticException e) { // Ujamemo aritm. izjemo             System.out.println("Prislo je do aritmetične napake!");         catch (Exception e) { // Ujamemo ostale izjeme             System.out.println("Prislo je do neke napake!");         }

Lovljenje izjem: try-catch-finally Po bloku catch lahko postavimo tudi blok finally, ki se bo izvršil v vsakem primeru, ne glede na to ali je do izjeme prišlo ali ne. Izvedel se bo tudi, če pride do izjeme v bloku catch!!! try {             for (int j=1;j<=10;j++) {                 x=x*j/y;                 y=y-1;             }             System.out.println("Rezultat je: " + y);         }         catch (Exception e) {             System.out.println("Prislo je do aritmetične napake!");             y=1/0;         finally { // izvede se, ceprav je v catch prišlo do izjeme!             System.out.println("To se izvede v vsakem primeru");         }

Stavek throws Ni potrebno, da vsakič postavljamo try-catch bloke. Za posamezne metode lahko s stavkom throws povemo, da v metodi lahko pride do neke izjeme. Tako se bo izjema prenesla na metodo, ki je to metodo klicala. Vse skupaj lahko poljubno gnezdimo. class racunaj {     // deli lahko povzroci izjemo!     static int deli(int x, int y) throws Exception {          return x/y;     } class main {     public static void main(String argv[ ]) {         int a=3; int b=0;                  try {             racunaj.deli(a,b);         }         catch (Exception e) {             System.out.println("Exception!!!");         }    

Stavek throw Izjemo lahko povzročimo tudi sami s stavkom throw: class racunaj {     // deli lahko povzroci izjemo!     static int deli(int x, int y) throws Exception {          if (y==0)             // sami povzročimo napako!             throw new Exception("Zgodila se je napaka");         else  return x/y;     } class main {     public static void main(String argv[ ]) {         int a=3; int b=0;                  try {             racunaj.deli(a,b);         }         catch (Exception e) {System.out.println(e.getMessage());   }