Handling Errors and Exceptions in Programming

Slide Note
Embed
Share

Learn how to manage errors and exceptions in programming using try, throw, and catch statements. Understand the types of errors - syntax, runtime, and logic errors - and how to prevent, detect, and handle them effectively to ensure your code runs smoothly.


Uploaded on Nov 23, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Managing Errors and Exceptions

  2. What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures. 2

  3. Syntax Errors, Runtime Errors, and Logic Errors Syntax errors arise because the rules of the language have not been followed. They are detected by the compiler. Runtime errors occur while the program is running if the environment detects an operation that is impossible to carry out. Logic errors occur when a program doesn't perform the way it was intended to. 3

  4. Introduction Rarely does the program run successful at its very first attempt. It is common to make the mistakes while developing as well as typing a program. A mistake might lead to an error causing to program to produce unexpected results. Errors are the wrongs that can make a program go wrong. An error may produce an incorrect result or may terminate the execution of the program abruptly or even may cause the system to crash.

  5. Types of Errors Errors may be broadly classified into two types. Compile time Errors Run Time Errors

  6. Compile Time Errors Compile time error means Java compiler identify the syntax error at the time of compilation. And without successfully compilation, compiler does not create .class file. That means we have to compile the program which should be error free and then compiler creates .class file of the program and then we can run the program.

  7. Compile Time Errors /* This Program Contains an Error class Error1 { public static void main(String args[]) { System.out.println( Hello Java ) } } Error1.java :7: : expected System.out.println( Hello java ) ^ 1 error

  8. Compile Time Errors Most compile-time errors are due to typing mistakes. The most common problems are : Missing semicolon Missing (or mismatch of ) brackets in classes and methods. Misspelling of identifiers and keywords Missing double quotes in strings. Use of undeclared variables Incompatible types in assignments /initialization Bad reference to objects Use of = in place of ==operator And so on

  9. Run Time Errors Several time program may compile successfully and compiler creates the .class file of the program. but when the time of running the program, it shows the error and that type of error called run time error. Such program may produce wrong results due to wrong logic or may terminate due to errors such as stack overflow.

  10. Run Time Errors Most Common run time errors are : Dividing an integer by Zero Accessing an element that is out of the bounds of an array. Trying to store a value into an array of an incompatible class or type. Trying to cast an instance of class to one of its subclasses. Passing a parameter that is not a valid range or value for a method. Trying to illegally change the state of thread. Attempting to use a negative size for an array. Converting invalid strings to number. And many more.

  11. Run Time Errors class errors2 { public static void main(String args[]) { int a=10,b=5,c=5; int x=a/(b-c); System.out.println( X= +x) int y=a/(b+c); System.out.println( Y= +y) } } Java.lang.ArithmeticException: / by zero at Error2.main(Error2.java:8

  12. What is an exception? Dictionary Meaning: Exception is an abnormal condition. An Exception is a condition that is caused by a run- time error in the program. When java interpreter encounters an error such as dividing an integer by zero, it creates an exception object and throws it.(i.e. informs us that error has occurred.)

  13. What is an exception? An Exception can be anything which interrupts the normal flow of the program. When an exception occurs program processing gets terminated and doesn t continue further. In such cases we get a system generated error message. The good thing about exceptions is that they can be handled.

  14. When an exception can occur? Exception can occur at runtime (known as runtime exceptions) as well as at compile-time (known Compile-time exceptions). Reasons for Exceptions There can be several reasons for an exception. For example, following situations can cause an exception - Opening a non-existing file, Network connection problem, Operands being manipulated are out of prescribed ranges, class file missing which was supposed to be loaded and so on.

  15. Why to handle exception? If an exception is raised, which has not been handled by programmer then program execution can get terminated and system prints a non user friendly error message. Ex:-Take a look at the below system generated exception Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionDemo.main(ExceptionDemo.java:5) For a novice user the above message won t be easy to understand. In order to let them know that what went wrong we use exception handling in java program. We handle such conditions and then prints a user friendly warning message to user.

  16. Types of exceptions There are two types of exceptions 1) Checked exceptions 2) Unchecked exceptions

  17. Checked exceptions All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the program, it will give compilation error. Examples of Checked Exceptions :- ClassNotFoundException IllegalAccessException NoSuchFieldException EOFException etc.

  18. Unchecked Exceptions Runtime Exceptions are also known as Unchecked Exceptions as the compiler do not check whether the programmer has handled them or not but it s the duty of the programmer to handle these exceptions and provide a safe exit. These exceptions need not be included in any method s throws list because compiler does not check to see if a method handles or throws these exceptions. Examples of Unchecked Exceptions:- ArithmeticException ArrayIndexOutOfBoundsException NullPointerException NegativeArraySizeException etc.

  19. Common java Exceptions Exception Meaning ArithmeticException Arithmetic error, such as divide-by-zero ArrayIndexOutOfBoundsException Array index is out-of-bounds ArrayStoreException Assigning an element of an incompatible type ClassCastException Invalid cast EnumConstantNotPresentException Attempt made to use undefined enumeration value IllegalArgumentException Illegal argument used to invoke a method IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread IllegalStateException Environment or application is in incorrect state IllegalThreadStateException Requested operation not compatible with current thread state IndexOutOfBoundsException Some type of index is out-of-bounds NegativeArraySizeException Array created with a negative size

  20. Exception NullPointerException NumberFormatException SecurityException StringIndexOutOfBoundsException TypeNotPresentException UnsupportedOperationException Meaning Invalid use of a null reference Invalid conversion of a string to a numeric format Attempt to violate security Attempt to index outside the bounds of a string Type not fount An unsupported operation was encountered ClassNotFoundException CloneNotSupportedException Class not found Attempt to clone an object that does not implement the Cloneable interface Access to a class is denied Attempt to create an object of an abstract class or interface One thread has been interrupted by another thread A requested field does not exist A requested method does not exist IllegalAccessException InstantiationException InterruptedException NoSuchFieldException NoSuchMethodException

  21. Exception hierarchy

  22. Exception Handling in Java Java allows Exception handling mechanism to handle various exceptional conditions. When an exceptional condition occurs, an exception is thrown. For continuing the program execution, the user should try to catch the exception object thrown by the error condition and then display an appropriate message for taking corrective actions. This task is known as Exception handling

  23. Exception Handling in Java This mechanism consists of : 1. Find the problem (Hit the Exception) 2. Inform that an error has occurred (Throw the Exception) 3. Receive the error Information (Catch the Exception) 4. Take corrective actions (Handle the Exception)

  24. Exception Handling in Java In Java Exception handling is managed by 5 keywords: try catch throw throws finally

  25. Exception Handling in Java Syntax of Exception Handling Code The basic concept of exception handling are throwing an exception and catching it. try Block try & catch Statement that causes Exception Catch Block Statement that handles the Exception

  26. What is Try Block? The try block contains a block of program statements within which an exception might occur. A try block must followed by a Catch block or Finally block or both. Syntax of try block try{ //statements that may cause an exception }

  27. What is Catch Block? A catch block must be associated with a try block. The corresponding catch block executes if an exception of a particular type occurs within the try block. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes. Syntax of try catch in java try{ //statements that may cause an exception } catch (Exception(type) e(object)) { //error handling code }

  28. class errors2{ public static void main(String args[]) { int a=10,b=5,c=5; try{ int x=a/(b-c); } catch(ArithmeticException e) { System.out.println( Division by zero ); } int y=a/(b+c); System.out.println( Y= +y) } }

  29. class Example1 { public static void main(String args[]) { int num1, num2; try { num1 = 0; num2 = 62 / num1; System.out.println("Try block message"); } catch (ArithmeticException e) { System.out.println("Error: Don't divide a number by zero"); } System.out.println("I'm out of try-catch block in Java."); } } Error: Don't divide a number by zero I'm out of try-catch block in Java.

  30. Multiple catch Statements try { //Protected code } catch(ExceptionType1 e1) { //Catch block } catch(ExceptionType2 e2) { //Catch block } catch(ExceptionType3 e3) { //Catch block }

  31. Sequence of Events Preceding step try block statement unmatched catch matching catch unmatched catch next step

  32. class Example2{ try{ int a[]=new int[7]; a[4]=30/0; System.out.println("First print statement in try block"); } public static void main(String args[]){ catch(ArithmeticException e){ System.out.println("Warning: ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Warning:ArrayIndexOutOfBoundsException");} catch(Exception e){ System.out.println("Warning: Some Other exception"); } System.out.println("Out of try-catch block..."); }}

  33. Multiple catch Statements A try block can have any number of catch blocks. A catch block that is written for catching the class Exception can catch all other exceptions. Syntax: catch(Exception e) { //This catch block catches all the exceptions } If multiple catch blocks are present in a program then the above mentioned catch block should be placed at the last as per the exception handling best practices.

  34. Nested try catch: The try catch blocks can be nested. One try-catch block can be present in the another try s body. This is called Nesting of try catch blocks. Each time a try block does not have a catch handler for a particular exception, the stack is unwound and the next try block s catch (i.e., parent try block s catch) handlers are inspected for a match. If no catch block matches, then the java run-time system will handle the exception.

  35. Syntax of Nested try Catch //Main try block try { statement 1; //try-catch block inside another try block try { statement 3;} catch(Exception e1) { //Exception Message } } catch(Exception e2) //Catch of Main(parent) try block { //Exception Message }

  36. What is Finally Block A finally statement must be associated with a try statement. It identifies a block of statements that needs to be executed regardless of whether or not an exception occurs within the try block. After all other try-catch processing is complete, the code inside the finally block executes. It will run regardless of whether an exception was thrown and handled by the try and catch parts of the block.

  37. Try-catch-finally In normal execution the finally block is executed after try block. When any exception occurs first the catch block is executed and then finally block is executed. Try { } catch( ) { } Finally { } Try { . } Finally { }

  38. Sequence of Events for finally clause Preceding step try block statement unmatched catch matching catch unmatched catch finally next step

More Related Content