OOP_L7.ppt
- Количество слайдов: 22
Обробка винятків Виняток – це ненормальна ситуація, яка виникає підчас виконання послідовності коду. Виняток Java – це об’єкт, який описує виняткову (тобто помилкову) ситуацію, яка виникає в частині програмного коду.
Ключові слова для обробки винятків try catch throws finally
Основи обробки винятків try { // блок коду, в якому відслідковуються помилки } catch ( Тип_винятку_1 ex. Ob) { // оброблювач винятку типу Exception. Type 1 } catch ( Тип_винятку_2 ex. Ob) { // оброблювач винятку типу Exception. Type 2 } // … finally { // блок коду, який повинен бути виконаний // після завершення блоку try }
Типи винятків Trowable Exception Error Runtime. Exception Users. Default
Винятки, які не обробляються class Exc 0 { public static void main(String args[]) { int d = 0; int a = 42 / d; } } java. lang. Arithmetic. Exception: / bу zero at Exc. O. main(Exc. O. java: 4) class Exc 1 { static void subroutine() { int d = 0; int a = 10 / d; } public static void main(String args[]) { Exc 1. subroutine(); } } java. lang. Arithmetic. Exception: / Ьу zero at Exc 1. subroutine(Exc 1. java: 4) at Exc 1. main(Exc 1. java: 7)
Використання try і catch (1) class Exc 2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System. out. println("This will not be printed. "); } catch (Arithmetic. Exception e) { // catch divide-by-zero error System. out. println("Division by zero. "); } System. out. println("After catch statement. "); } } Division by zero. After catch statement.
Використання try і catch (2) import java. util. Random; class Handle. Error { public static void main(String args[]) { int a=0, b=0, c=0; Random r = new Random(); for(int i=0; i<32000; i++) { try { b = r. next. Int(); c = r. next. Int(); a = 12345 / (b/c); } catch (Arithmetic. Exception e) { System. out. println("Division by zero. "); a = 0; // set a to zero and continue } System. out. println("a: " + a); } } } Division by zero. a: 0
Відображення опису винятку Object to. String() catch (Arithmetic. Exception e) { System. out. println("Exception: " + e); a = 0; // set a to zero and continue } Exception: java. lang. Arithmetic. Exception: / Ьу zero Throwable to. String()
Множинні оператори catch (1) class Multi. Catch { C: >java Multi. Catch public static void main(String args[]) { a=0 try { Divide by 0: int a = args. length; java. lang. Arithmetic. Exception: / Ьу zero System. out. println("a = " + a); After try/catch blocks. int b = 42 / a; int c[] = { 1 }; c[42] = 99; C: >java Multi. Catch Test. Arg } catch(Arithmetic. Exception e) { a=1 System. out. println("Divide by 0: " + e); } catch(Array. Index. Out. Of. Bounds. Exception e) { Array index oob: System. out. println("Array index oob: " + e); java. lang. Array. Index. Out. Of. Bounds } Exception: 42 System. out. println("After try/catch blocks. "); After try/catch blocks. } }
Множинні оператори catch (2) class Super. Sub. Catch { public static void main(String args[]) { try { int a = 0; int b = 42 / a; } catch(Exception e) { System. out. println("Generic Exception catch. "); } /* This catch is never reached because Arithmetic. Exception is a subclass of Exception. */ catch(Arithmetic. Exception e) { // ERROR unreachable System. out. println("This is never reached. "); } } }
Вкладені оператори try (1) class Nest. Try { public static void main(String args[]) { try { int a = args. length; /* If no command line args are present, the following statement will generate a divide-by-zero exception. */ int b = 42 / a; System. out. println("a = " + a); try { // nested try block /* If one command line arg is used, then an divide-by-zero exception will be generated by the following code. */ if(a==1) a = a/(a-a); // division by zero /* If two command line args are used then generate an out-of-bounds exception. */ if(a==2) { int c[] = { 1 }; c[42] = 99; // generate an out-ofbounds exception } } catch(Array. Index. Out. Of. Bounds. Exception e) { System. out. println("Array index out-ofbounds: " + e); } } catch(Arithmetic. Exception e) { System. out. println("Divide by 0: " + e); } } }
Вкладені оператори try (2) C: >java Nest. Try Divide by 0: java. lang. Arithmetic. Exception: / Ьу zero C: >java Nest. Try One a=1 Divide by 0: java. lang. Arithmetic. Exception: / Ьу zero C: >java Nest. Try One Two a=2 Array index oob: java. lang. Array. Index. Out. Of. Bounds. Exception: 42
Вкладені оператори try (3) class Meth. Nest. Try { static void nesttry(int a) { try { // nested try block /* If one command line arg is used, then an divide-by-zero exception will be generated by the following code. */ if(a==1) a = a/(a-a); // division by zero /* If two command line args are used then generate an out-of-bounds exception. */ if(a==2) { int c[] = { 1 }; c[42] = 99; // generate an out-ofbounds exception } } catch(Array. Index. Out. Of. Bounds. Exception e) { System. out. println("Array index out-ofbounds: " + e); } } public static void main(String args[]) { try { int a = args. length; /* If no command line args are present, the following statement will generate a divide-by-zero exception. */ int b = 42 / a; System. out. println("a = " + a); nesttry(a); } catch(Arithmetic. Exception e) { System. out. println("Divide by 0: " + e); } } }
Використання ключового слова throw (1) throw екземпляр_Throwable;
Використання ключового слова throw (2) class Throw. Demo { static void demoproc() { try { throw new Null. Pointer. Exception("demo"); } catch(Null. Pointer. Exception e) { System. out. println("Caught inside demoproc. "); throw e; // re-throw the exception } } public static void main(String args[]) { try { demoproc(); } catch(Null. Pointer. Exception e) { System. out. println("Recaught: " + e); } } } Caught inside demoproc. Recaught: java. lang. Null. Pointer. Exception: demo
Використання ключового слова throws (1) тип ім’я_методу(список_параметрів) throws список_винятків { // тіло методу }
Використання ключового слова throws (2) class Throws. Demo { static void throw. One() throws Illegal. Access. Exception { System. out. println("Inside throw. One. "); throw new Illegal. Access. Exception("demo"); } public static void main(String args[]) { try { throw. One(); } catch (Illegal. Access. Exception e) { System. out. println("Caught " + e); } } } Inside throw. One. Caught java. lang. Illegal. Access. Exception: demo
Використання ключового слова finally class Finally. Demo { // Through an exception out of the method. static void proc. A() { try { System. out. println("inside proc. A"); throw new Runtime. Exception("demo"); } finally { System. out. println("proc. A's finally"); } } // Return from within a try block. static void proc. B() { try { System. out. println("inside proc. B"); return; } finally { System. out. println("proc. B's finally"); } } // Execute a try block normally. static void proc. C() { try { System. out. println("inside proc. C"); } finally { System. out. println("proc. C's finally"); } } public static void main(String args[]) { try { proc. A(); } catch (Exception e) { System. out. println("Exception caught"); } proc. B(); proc. C(); } }
Вбудовані винятки Винятки, які не перевіряються Підкласи Run. Time. Exception (java. lang) 1. Arithmetic. Exception 2. Arraylndex. Oиt. Of. Boиnds. Exception 3. Array. Store. Exception 4. Class. Cast. Exception 5. Enиm. Constant. Not. Present. Exception 6. Illegal. Argиment. Exception 7. Illegal. Monitor. State. Exception 8. Illegal. State. Exception 9. Illegal. Thread. State. Exception 10. Index. Oиt. Of. Boиnds. Exception 11. Negative. Array. Size. Exception 12. Nиll. Pointer. Exception 13. Nиmber. Format. Exception 14. Secиrity. Exception 15. Stringlndex. Oиt. Of. Boиnds 16. Type. Not. Present. Exception 17. Unsиpported. Operation. Exception Винятки, які перевіряються (java. lang) Class. Not. Foиnd. Exception Clone. Not. Supported. Exception Illegal. Access. Exception Instantiation. Exception Interrиpted. Exception No. Sиch. Field. Exception No. Sиch. Мethod. Exception
Створення власних класів винятків (1) Методи, визначені в Throwable Throwable fill. In. Stack. Trace() Throwable get. Cause() String get. Localized. Мessage() String get. Message() Stack. Trace. Element[] get. Stack. Trace() Throwable init. Cause( Throwable исключение) void print. Stack. Trace(Print. Stream ПОТОК) void print. Stack. Trace(Print. Writer ПОТОК) void set. Stack. Trace( Stack. Trace. Element элементы[]) String to. String()
Створення власних класів винятків (2) class My. Exception extends Exception { private int detail; My. Exception(int a) { detail = a; } public String to. String() { return "My. Exception[" + detail + "]"; } } class Exception. Demo { static void compute(int a) throws My. Exception { System. out. println("Called compute(" + a + ")"); if(a > 10) throw new My. Exception(a); System. out. println("Normal exit"); } public static void main(String args[]) { try { compute(1); compute(20); } catch (My. Exception e) { System. out. println("Caught " + e); } } }
Створення власних класів винятків (3) Called compute (1) Normal exit Called compute (20) Caught My. Exception [20]
OOP_L7.ppt