JAVA ASSIGNMENT EXCEPTION .Exceptional event. . Error that occurs during runtime. . Cause normal program flow to be disrupted. . Examples- Divide by zero errors. - Accessing the elements of an array beyond its range . - Invalid Input. . An exception can occur for many different reasons, including the following: - A user has entered invalid data. - A file that has needs to be opened cannot be found. - A network connections has been lost in the middle of communication, or the JVM has run out of memory. “If the exception object is not handled properly, it will display the error and will terminate the program”. . EXCEPTION TYPES
. Exception are of two types-Built-in Exceptions -User Defined Exceptions
Built -in Exceptions . Built -in exceptions are the exception which are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in Exceptions in Java. 1) Arithmetic Exception It is thrown when an exceptional condition has occurred in an arithmetic operation. 2) ARRAYINDEXOUTOFBOUNDEXCEPTION It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to size of the array. 3) Class Not Found Exception This Exception is raised when we try to access a class whose definition is not found. 4) File Not Found Exception This Exception is raised when a file is not accessible or does not open. 5) IO Exception It is thrown when an input – output operation failed or interrupted. 6) Interrupted Exception It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted. 7) Null Pointer Exception This exception is raised when referring to the members of a null object. Null represents nothing. Example// Java program to demonstrate Arithmetic exception Class Arithmetic Exception _ Demo Public static void main (string args [ ] ) { Try { Int a = 30, b = 0 ;
Int c = a/b; // cannot divide by zero System.out.println ( “Result = “ + c ); }
Catch ( Arithmeticexception e) { System .out.println(“ Cant’t divide a number
by 0”);
User -defined Exception Sometimes, the built -in exceptions in java are not able to describe a certain situation. In such cases, user can also create exceptions which are called ‘user -defined Exception’. Following steps are followed for the creation of user- defined exception. . The user should create an exception class as a subclass of exception class. Exception class, the user should also make his class a subclass of it. . We can write a default constructor in his own exception class. . We can also create a parameterized constructor with a string as a parameter. We can call super class (exception) constructor from this and send the string there. . To raise exception of user-defined type, we need to create an object to his exception class and throw it using throw clause asMy exception me = new exception(“Except ion details”); Throw me; . The following program illustrates how to create own exception class My exception.
.EXCEPTION BLOCK There are two Block of exception in Java they are
1) Try Block- It is used to enclose the code that might throw an exception. It must be used within the method. If an exception occurs at the particular statement of try block, the rest of the block code will not be executed. So, it is recommended not to keeping the code in try block that will not throw an exception. Java try must be followed by either catch or finally block. Syntax of Java try-catch Try { //code that may throw an exception } catch(Exception_class_Name ref){ } 2) Catch Block- It is used to handle the exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( Exception) or the generated exception type. However, the good approach is to declare the generated type of exception. The catch block must be used after the try block only. You can use multiple catch block with a single try block
VARIOUS COMMON EXCEPTION An exception is an abnormal condition that occurs in a code sequence during the execution of a program.
Some common exception are CHECKED EXCEPTIONS Checked exception are mandatory to handle. They are direct subclasses of the Exception. IOEXCEPTION A method throws an IO Exception or a direct subclass of it when any Input/output operation fails. Types uses of these I/O operations include – . Working with the file system or data streams using java.io package. . creating network applications using java.net package. FILE NOT FOUND EXCEPTION File not found exception is a common type of IO exception while working with the file system.
INTERRRUPTED EXCEPTION Whenever a java thread calls join(),sleep(), or wait() it goes into either the WAITING state or the TIMED_WAITING state. In addition, a thread can interrupt another thread by calling another thread’s interrupt () method.
UNCHECKED EXCEPTIONS For unchecked exceptions, the compiler doesn’t check during the compilation process. Hence, it isn’t mandatory for the method to handle these exceptions. All unchecked exceptions extend the class run time Exception.
NULL POINTER EXCEPTION If an application attempts to use null where it actually requires an object instance, the method will throw a null pointer exception. There are different scene where illegal uses if null causes Null pointer exception. Let’s consider some of them. Calling a method of the class that has no object instance.
ARRAY INDEX OUT OF BOUNDS EXCEPTIO An array stores its elements in contiguous fashion. Thus, we can access its elements via indices. However, if a piece of code tries to access an illegal index of an array, the respective method throws an array index out of bound exception.
STRING INDEX OUT OF BOUND EXCEPTION The string class in Java provides the methods to access a particular character array out of the string. When we use these methods, internally it converts the string into a character array. Again, there could be an illegal use of indexes on this array. In such cases, these methods of string class throw the string index out of bound exception. This exception indicates that the index is either greater than or equal to the size of the string. String index out of Bounds exception extends index out of bound exception.
NUMBER FORMAT EXCEPTION Quite often an application ends up with numeric data in a String. In order to interpret this data as numeric. Java allow the conversion of
String to numeric types. The wrapper classes such as Integer. Float, etc. contains utility methods for this purpose. However, if the string doesn’t have an appropriate format during the conversion, the method throws a Number format exception.
CLASS CAST EXCEPTION Java allows typecasting between the objects in order to support inheritance and polymorphism. We can either up cast an object or downcast it. In up casting, we cast an object to its supertype. And in down casting, we can cast an object to one of its subtypes.
ILLEGAL ARGUMENT EXCEPTION A method throws an illegal argument exception if we call it with some illegal or inappropriate arguments.
ILLEGAL STATE EXCEPTION Illegal state exception signals that a method’s been involved at an illegal or inappropriate time. RUN TIME EXCEPTION Runtime exception is the superclass of those exception that can be thrown during the normal operation of the Java virtual machine. A method is not required to declare in its throw clause any subclasses of Runtime Exception that might be thrown during the execution of the method but not caught. Runtime and its subclasses are unchecked exceptions .Unchecked exceptions do not need to be declared in a method or construct’s
throw clause if they can be executed of the method or constructor and propagate outside the method or constructor boundary.
COMPILE TIME EXECUTION 1) Compile time is when the program is compiled. 2) It is when your code started to compile by JVM and it will check for the syntax error in the code everything is done in compile is processed by the JVM. 3) The program need not satisfy any invariants. In facts, it needn’t be a well-formed program at all. You could feed this html to the compiler and watch it barf. 4) Syntax errors, Type checking errors, compiler crashes can go wrong in compile time. 5) It is the instance where the code you entered is converted to execution.
EXCEPTION KEYWORDS 1) 2) 3) 4) 5)
Try Catch Finally Throw Throws 1) Try Block- It is used to enclose the code that might throw an exception. It must be used within the method. If an exception occurs at the particular statement of try block, the rest of the block code will not be executed. So, it is recommended not to keeping the code in try block that will not throw an exception. Java try must be followed by either catch or finally block. Syntax of Java try-catch
Try { //code that may throw an exception } catch(Exception_class_Name ref){ } 2) Catch Block- It is used to handle the exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( Exception) or the generated exception type. However, the good approach is to declare the generated type of exception. The catch block must be used after the try block only. You can use multiple catch block with a single try block 3) FINALLY BLOCK- It is a block that is used to execute important code such as closing connection, stream etc. Java finally block is always executed whether exception is handled or not. It block follows try or catch block. 4)THROW- The throw keyword in java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. It is mainly used to throw custom exceptions. 5) THROWS- It is a keyword in java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try- catch block.