The Intel 8086 microprocessor, designed by Intel in the late 1970s, is an 8-bit/16-bit microprocessor and the first member of the x86 family of microprocessors1. Here’s a brief overview of its internal architecture:
Complex Instruction Set Computer (CISC) Architecture: The 8086 microprocessor is ...
The Intel 8086 microprocessor, designed by Intel in the late 1970s, is an 8-bit/16-bit microprocessor and the first member of the x86 family of microprocessors1. Here’s a brief overview of its internal architecture:
Complex Instruction Set Computer (CISC) Architecture: The 8086 microprocessor is based on a CISC architecture, which supports a wide range of instructions, many of which can perform multiple operations in a single instruction1.
Bus Interface Unit (BIU): The BIU is responsible for fetching instructions from memory and decoding them, while also managing data transfer between the microprocessor and memory or I/O devices1.
Execution Unit (EU): The EU executes the instructions1.
Memory Segmentation: The 8086 microprocessor has a segmented memory architecture, which means that memory is divided into segments that are addressed using both a segment register and an offset1.
Registers: The 8086 microprocessor has a rich set of registers, including general-purpose registers, segment registers, and special registers
Size: 507.4 KB
Language: en
Added: May 29, 2024
Slides: 44 pages
Slide Content
Unit 4
What is Exception Exception is an abnormal condition that arises when executing a program. In the languages that do not support exception handling, errors must be checked and handled manually, usually through the use of error codes. In contrast, Java: handle errors. the absence of Provides syntactic mechanisms to signal, detect and Ensures a clean separation between the code executed in errors and the code to handle various kinds of errors. Brings run-time error management into object-oriented programming. An exception is an object that describes an exceptional condition (error) that has occurred when executing a program. Exception handling involves the following: when an error occurs, an object (exception) representing this error is created and thrown in the method that caused it that method may choose to handle the exception itself or pass it on either way, at some point, the exception is caught and processed
When and how it happens An exception can occurs for many different reasons, below are the some scenorio where exception occurs. A user has entered invalid data. A file that need to be opened cannot be found. A network connection has been lost in the middle of the communication or the JVM has run out of the memory. Java Exception handles as follow Find the problem (Hit the ecxeption) Inform that an error has occurred ( throw the Exception) Receive the error information(Catch the exception) Take corrective action ( Handle the Exception)
Types of Exception(Exception Hierarchy)
C o n t … Runtime Exception or Unchecked Exception class The exception which are not checked by compiler are called unchecked exception. Compiler do not produce error whether you handle or ignore unchecked exception. E.g. A r ithe m atic E x ceptio n , NullPoiterException
Exception class has two main subclasses IOException or Checked Exception class Exception that are checked and handle a compile time are checked exception. Checked exception occurs when the chances of failures are too high. E.g. FileNotFoundException, IOException
Example //Uncaught exception class Uncaught { public static void main(String args[]) { int x = 23; int y = 0; System.out.println(x/y); } } Output Exception in thread "main" java.lang.ArithmeticException: / by zero at Uncaught.main(Uncaught.java:8)
What is Error? Errors are mistakes that can make program go wrong. Error may be logical or may be typing mistake. An error may produce an incorrect output or Error terminate the execution of program abruptly or Error may cause the system to be crash.
Types of Error Compile time errors Runtime errors
Compile Time Error All syntax errors will be detected and displayed by java compiler and therefore these errors are known as compile time errors. The most of common problems are: Missing semicolon Missing (or mismatch of) bracket in classes & methods Misspelling of identifiers & keywords Missing double quotes in string Use of undeclared variables. Bad references to objects.
Example 1: Misspelled variable name or method names class MisspelledVar { public static void main(String args[]) { int a = 40, b = 60; // Declared variable Sum with Capital S int Sum = a + b; // Trying to call variable Sum // with a small s ie. sum System.out.println( "Sum of variables is " + sum); } } Example 2: Missing semicolons class PrintingSentence { public static void main(String args[]) { String s = “Vidyalankar Polytechnic"; // Missing ';' at the end System.out.println("Welcome to " + s) } } Example of Compile time error
Runtime Error Programs may produce wrong results due to wrong logic or may terminate due to errors such as stack overflow. When such errors are encountered java typically generates an error message and aborts the program. The most common run-time errors are: Dividing an integer by zero Accessing an element that is out of bounds of an array Trying to store value into an array of an incompatible class or type Passing parameter that is not in a valid range or value for method Trying to illegally change status of thread Attempting to use a negative size for an array Converting invalid string to a number Accessing character that is out of bound of a string
Example of Run time error Example: Runtime Error caused by dividing by zero class DivByZero { public static void main(String args[]) { int var1 = 15; int var2 = 5; int var3 = 0; int ans1 = var1 / var2; // This statement causes a runtime error, // as 15 is getting divided by here int ans2 = var1 / var3; S y s t e m .o u t .p r i n t l n( "Division of va1" + " by var2 is: " + ans1); S y s t e m .o u t .p r i n t l n( "Division of va1" + " by var3 is: " + ans2); }}
Concept Explination Both java.lang.Error and java.lang.Exception classes are sub classes of java.lang.Throwable class , but there exist some significant differences between them. java.lang.Error class represents the errors which are mainly caused by the environment in which application is running. For example, OutOfMemoryError occurs when JVM runs out of memory or StackOverflowError occurs when stack overflows. Where as java.lang.Exception class represents the exceptions which are mainly caused by the application itself. For example, NullPointerException occurs when an application tries to access null object or ClassCastException occurs when an application tries to cast incompatible class types.
Difference Between error and exception Sr. No. Exception Error 1. You can recover from exception by handling them through try catch block. It is impossible to recover from error 2. Exception can be classified into two types: Checked Exception Unchecked Exception There is no such classification for errors. Errors are always unchecked. 3. Can occur at runtime or compile time due to an issue in the program Occur at runtime due to lack of system recourses. 4. In case of checked exception compiler would have knowledge of checked exception and force to keep try catch block. In case of error compiler wont have knowledge of errors. 5 Exceptions in java are of type java.lang.Exception. Errors in java are of type java.lang.Error. 6. e.g. ArithematicException SQLException e.g. OutOfMempryError StackOverflowError
try, catch and finally block An exception is an event, which occurs during the execution of a program, that stop the flow of the program's instructions and takes appropriate actions if handled. Exceptional handling mechanism provides a means to detect errors and throw exceptions, and then to catch exceptions by taking appropriate actions. Java Exception handles as follow Find the problem (Hit the exception) Inform that an error has occurred ( throw the Exception) Receive the error information(Catch the exception) Take corrective action ( Handle the Exception) Exceptional handling in java by five keywords are as follows: try catch finally throw throws
try block try: This block applies a monitor on the statements written inside it. If there exist any exception, the control is transferred to catch or finally block. Syntax: try { // block of code to monitor for errors }
catch block Catch: This block includes the actions to be taken if a particular exception occurs. Syntax: catch ( ExceptionType1 exOb ) { // exception handler for ExceptionType1 }
try and catch
Example of Multiple catch block It is possible to have multiple catch block in our program
Concept of Nested Try The nested try is used to implement multiple try statements in a single block of main method. Syntax: - Try { Try { } } The try statement can be nested. That is, a try statement can be used inside the block of another try. Each time when a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match of exception.
C o n t … This continues until one of the catch statements succeeds, or until all the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception
Example of Nested Try // N e st e d t r y b loc k s import java.util.Scanner; class NestTry { public static void main(String args[]) { int x , z ; S c anne r in = ne w S c anner( S y st e m .i n) ; S y s t e m . o u t .pr i nt ( " E n t e r nu m be r : " ) ; x = in .ne x t I n t (); try { z = 8 2 / x ; / / st a t e m en t1 System.out.println("Division: "+z); try { int a = 10 / ( x -1) ; / / st a t e m en t2 s hor t arr [] = { 15} ; arr [ 10 ] = 25 ; / / st a t e m en t3 System.out.println("Inner try end..."); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array indexing wrong"); } System.out.println("Outer try end..."); } catch(ArithmeticException e) //2 { System.out.println("Division by zero"); } System.out.println("Program end..."); } }
Concept of finally block finally: finally block includes the statements which are to be executed in any case, in case the exception is raised or not Syntax: finally { // block of code to be executed before try block ends }
Example of finally class FinallyClause { public static void main(String args[]) { try { // int v a l = ; / / st a t e m en t1 // i n t m = 10 / v a l; / / s t a t e m en t2 int [ ] x = ne w in t [ -5 ]; / / st a t e m en t3 System.out.println("No output"); } catch(ArithmeticException e) { System.out.println("Exception: "+e); Now, if we removed the comments from statement1 and statement2, the output will be: } finally { System.out.println("Program end"); System.out.println("Bye bye..."); } } }
Concept of throw throw: This keyword is generally used in case of user defined exception, to forcefully raise the exception and take the required action. Syntax: throw throwable instance;
Demonstration of throw clause // D e m on s t ra ti o n o f t h ro w cl au se class ThrowDemo { public static void main(String args[]) { int x = 10 , y = 20 ; i n t z; z = x + y ; try { throw new ArithmeticException(); } catch(Exception e) { System.out.println("Exception caught"); System.out.println("Addition: "+z); } } } Output: Exception caught Addition: 30
Concept of throws throws : throws keyword can be used along with the method definition to name the list of exceptions which are likely to happen during the execution of that method. In that case , try … catch block is not necessary in the code. Syntax: Type method-name (parameter list) throws exception list { // body of method }
Distinguish between throw and throws Sr. No. throw throws 1 Whenever we want to force an exception then we use throw keyword. when we know that a particular exception may be thrown or to pass a possible exception then we use throws keyword. 2 "Throw" is used to handle user-defined exception. JVM handles the exceptions which are specified by "throws". 3 I t c a n a lso pa ss a c u s t o m m e ss ag e to y ou r exceptionhandling module. Point to note here is that the Java compiler very well knows about the exceptions thrown by some methods so it insists us to handle them. 4 Throw keyword can also be used to pass a custom message to the exception handling module i.e. the message which we want to be printed. W e c a n a lso u se t hro w s cla u se o n t h e s urround ing method instead of try and catch exception handler. 5 Throw is used to through exception system explicitly. Throws is used for to throws exception m ean s t h ro w s i o e x c ep ti o n and servletexception and etc. 6 Throw is used to actually throw the exception. Whereas throws is declarative for the method. They are not interchangeable. 7 I t is u s e d to genera te a n e x c ep ti on . I t is u s e d to f o r w ar d a n e x c ep ti on .
What is Built-in Exception Built-in exceptions are the exceptions which are available in Java libraries. Java defines several exception classes inside the standard package java.lang . These exceptions are suitable to explain certain error situations. The most general of these exceptions are subclasses of the standard type RuntimeException. Since java.lang is implicitly imported into all Java programs, most exceptions derived from RuntimeException are automatically available. An exception is an object that describes an exceptional condition (error) that has occurred when executing a program. Exception handling involves the following: when an error occurs, an object (exception) representing this error is created and thrown in the method that caused it that method may choose to handle the exception itself or pass it on either way, at some point, the exception is caught and processed
Unchecked RuntimeException Sr. No. Exception Description 1 ArithmeticException Arith m etic err o r, such as di v ide -b y - zer o . 2 ArrayIndexOutOfBoundsException Array index is out-of-bounds. 3 ArrayStoreException Assignment to an array element of an incompatible type. 4 ClassCastException Invalid cast. 5 IllegalArgumentException Illegal argument used to invoke a method. 6 IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
Sr. No. Exception Description 7 IllegalStateException Environment or application is in incorrect state. 8 IllegalThreadStateException Requested operation not compatible with the current thread state. 9 IndexOutOfBoundsException Some type of index is out-of-bounds. 10 NegativeArraySizeException Array created with a negative size. 11 NullPointerException Invalid use of a null reference. 12 NumberFormatException Invalid conversion of a string to a numeric format. Sr. No. Exception Description 13 SecurityException At t e m pt to v iol a te securit y . 14 StringIndexOutOfBounds Attempt to index outside the bounds of a string. 15 UnsupportedOperationException An unsupported operation was encountered.
Checked Exceptions Sr.No. Exception Description 1 ClassNotFoundException Class not found. 2 CloneNotSupportedException Atte m pt to clone an object that does not i m ple m ent the Cloneable interface. 3 UnsupportedOperationException An unsupported operation was encountered. 4 IllegalAccessException Access to a class is denied 5 InstantiationException Attempt to create an object of an abstract class or interface 6 InterruptedException One thread has been interrup t ed by another thread. 7 NoSuchFieldException A requested field does not exist. 8 NoSuchMethodException A requested method does not exist.
Chained Exception Chained Exception was added to Java in JDK 1.4. This feature allows you to relate one exception with another exception, i.e one exception describes cause of another exception. Two new constructors and two new methods were added to Throwable class to support chained exception. Throwable (Throwable cause) Throwable (String str, Throwable cause) getCause() and initCause() are the two methods added to Throwable class. getCause() method returns the actual cause associated with current exception. initCause() set an underlying cause(exception) with invoking exception.
Example: Chained Exception Public class test { public static v oid m ain ( String ar g []) { try { method1(); } Catch (Exception exception) { e x ception.p r in t S t a c k .t r a c e ( ) ; } } Public static v oid m ethod1() throw E x ception { try { Method2(); } Catch (Exception exception) { Throw new Exception(“Exception thrown in method1”+exception); } } Public static v oid m ethod2() throw E x ception { try { Method3(); } Catch (Exception exception) { Throw new Exception (“Exception thrown in m e t hod2 ” + e x c ep t ion); } } Public static void method3() throw Exception { throw new Exception (“Exception thrown in method3 ”); } }
Concept Explanation We learned about Java exceptions. We know that exceptions abnormally terminate the execution of a program. This is why it is important to handle exceptions. Here's a list of different approaches to handle exceptions in Java. try...catch block finally block throw and throws keyword
Creating Own Exception/User Define Exception Java provides us facility to create our own exceptions which are basically derived classes of Exception . Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, a user can also create exceptions which are called ‘User-Defined Exceptions’. User Defined Exception or custom exception is creating your own exception class and throws that exception using ‘throw’ keyword. This can be done by extending the class Exception. Key points A user-defined exception must extend Exception class. The exception is thrown using throw keyword.
class NegativeOutputException extends Exception { private int det; NegativeOutputException(int a) { de t = a ; } public String toString() { return "NegativeOutputException["+det+"]"; } } class OwnException { public static void main(String args[]) { int x = I n t eger . par s e I nt( a rg s [ ] ) ; i n t y = I n t e ger . p ar s e I n t ( a rg s[ 1 ] ) ;; int z; try { z = x * y ; if(z<0) //statement1 throw new NegativeOutputException(z); System.out.println("Output: "+z); } catch (NegativeOutputException e) { System.out.println("Caught: "+e); } } } Example 1: Creating our own exception.
Example 2: Define an exception called “No match Exception‟ that is thrown when a string is not equal to “MSBTE”. import java.io.*; class NoMatchException extends Exception { NoMatchException(String s) { super(s); } } c la s s t e st 1 { public static void main(String args[]) throws IOException { BufferedReader br= new BufferedReader(new I n p u tSt r e a m R e a d e r ( S y st e m . in) ) ; System.out.println("Enter a word:"); String str= br.readLine(); try { if ( st r .c o m pare T o ( " M SB T E " ) ! = ) / / c a n b e don e w i t h equals() throw new NoMatchException("Strings are not equal"); else S y st e m . ou t. pr i n t l n ( " S t r i n g s ar e equa l" ) ; } catch(NoMatchException e) { System.out.println(e.getMessage()); } } }
import java.io.*; class Negative extends Exception { Negative(String msg) { super(msg); } } class Negativedemo { public static void main(String ar[]) { int age=0; String name; BufferedReaderbr=new BufferedReader (new InputStreamReader(System.in)); System.out.println("enter age and name of person"); try { age=Integer.parseInt(br.readLine()); name=br.readLine(); { if(age<0) throw new Negative("age is negative"); else System.out.println("age is positive"); } } catch(Negative n) { System.out.println(n); } catch(Exception e) { } } } Example 2: Write a program to input name and age of person and throws user defined exception, if entered age is negative
Exception in Subclass/ Exception Handling with Method Overriding When Exception handling is involved with Method overriding, ambiguity occurs. The compiler gets confused as which definition is to be followed. Such problems were of two types: If the superclass method does not declare an exception If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception. If the superclass method declares an exception If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.
import java.io.*; class SuperClass { // SuperClass doesn't declare any exception void method() { System.out.println("SuperClass"); } } // SuperClass inherited by the SubClass class SubClass extends SuperClass { // method() declaring Checked Exception IOException void method() throws IOException { // IOException is of type Checked Exception // so the compiler will give Error System.out.println("SubClass"); } public static void main(String args[]) { SuperClass s = new SubClass(); s.method(); } } If the superclass method does not declare an exception
If the superclass method declares an exception import java.io.*; public static void main(String args[]) class SuperClass { // SuperClass declares an exception void method() throws RuntimeException { System.out.println("SuperClass"); } } // SuperClass inherited by the SubClass class SubClass extends SuperClass { // SubClass declaring a child exception // of RuntimeException void method() throws ArithmeticException { // ArithmeticException is a child exception // of the RuntimeException // So the compiler won't give an error System.out.println("SubClass"); } { SuperClass s = new SubClass(); s.method(); } } Page 44 Maharashtra State Board of Technical Education 2 Feb 2021