0% found this document useful (0 votes)
57 views55 pages

Java Unit-2 One Shot Marathon Notes

sdada

Uploaded by

d.devilmc05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
57 views55 pages

Java Unit-2 One Shot Marathon Notes

sdada

Uploaded by

d.devilmc05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 55
leat eee Koo) Fe JAVA. Unit-2 ONE SH© Exception Handling( py; Vikas Sir B® Unit No: 2 ( Exception Handling) Exception in java: * In Java, Exception is an(unwanted or unexpected levent, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. * Exceptions can be(caught and handled bythe program. * When an exception occurs, Ja’ a(creates an object] at represents[the error, This object is called an" * The exception object contains information about the error, like(fts typqand Java Programming by VikasSir an exception Occurs: * Invalid user input —— * Device failure — a * Loss of network conne: * Out of bound * Type mismatch — * Opening an unavailable fil * Database erro! * Arithmetic errors eption Handling: * Exception Handling is a(mechanism to handle runtime errorsbuch as ClassNotFoundException, |OException, SQLException, RemoteException, etc~ * The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions. * Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc. 2 natement 1" statement 2; f * statement 4; * statement 5; * statement 6; * statement 7; Types Of Exception in java: ser Defined/Customer Defined: * Auser-defined exception in Java is aCustom error/type that you create to handle &pecific situations in your program|\that aren't covered by Java's built-in exceptions. * User-defined exceptions make it easier to\understand the codejand improve its (naintainability| by providing @reaningful error messaged.and handling speci « User-defined exceptions can be used to create(modular code, jmaking it easier to manage complex and large applications, « User-defined exceptions can provide more information about the error, making it easier to diagnose and fix the problem. Customer Based Exception: // Custom exception class — public class|MyCustomException, xtends Exception { // Constructor that accepts a custom error message public MyCustomException(String message) { super(message); // Call the constructor of the|Exception class, } } S Java Programming by Vikassir = Inbuilt Exception: * In Java, inbuilt exceptions refer to the exceptions that are provided by the Javagtandard Ubrary-]_ * These exceptions are predefined and are available for use in Java * Inbuilt exceptions are typically organized into a hierarchy of exception classes, with the base class bei java.lang.Exceptiot Examples of inbuilt exceptions include: * NullPointerException: This exception is thrown when a program attempts to access or manipulate an object reference that has a null value. String str = nu! L System.out.printl length());// Thi NullPointerExcepti ystem.out.prin' - ngt 7 rows NullPointerException © ArithmeticException: This exception is thrown when an arithmetic operation such as division by zero occurs, — int result = 10/0; // Throws ArithmeticExcep* lojo Dp Checked Exception: * Checked exceptions are exceptions that are €hecked at compile-time. it must either handle the exception(within a try-catch block orfdeclare it din the method signatureJif neither is done, the code will not compile, — © SQLExceptio: Examples of Checked Exceptions: én econ + FileNotFoundException — . ClassNotFoundexception Java Programming by Vikassir = Example: import java.io. FileInputStream; import java.io. FileNotFoundException; _-piiblic class Main { a public static void main(String args []){ —— =a // Attempt to open a file FileinputStream file = new Filel mutstrean(itesoe), | } =, catch (FileNotFoundException e) { // Handle the exception System.out.println("file not found: " + gee cesea: Py 2 output: file not found;fite.txt*/(No such file or directory) S Unchecked Exceptions in Java: « Unchecked exceptions in Java are exceptions that are not checked at Gompile-time. | * This ins the Java compiler does not force the programmer to handle or declare these exceptions. — * Unchecked exceptions are typically used to(signal programming errors, such as logic errors or improper fan API. RuntimeException. Common subclasses include: 7 MullPointerException intl '-ArrayindexOutOfBoundsException- ~~ J _» ArithmeticException Gi 12) * IllegalArgumentException lassCastException « Example: public class Mai! — Public static void main(String[] args) { int[] arr = a, a aus > @® tri MW nol to access an index out of bounds Le arri5]; Fal Gis TOS eateh (ArraylndexOutOfBoundsException e) { // Handle the exception System.out.printin("(A } "+ e.getMessage()); " it of bounds forilength 3 Output: Array index out of bounds: Inde) ee Difference between checked and un-checked exception: S.No. Aspect Checked exceptions | Unchecked exceptions st be caught or Need not be explicitly - Za declared. handled or declared. 2. Example TOException J |NutPointerException 3. Compilation ginoten by the get checked by the compiler. compiler. S Aspect Checked exceptions Unchecked exceptions Must be handled with | Can be handled optionally Handling catch or| with try-catchlif clause. necessary. ee : P factors (e.g., 1/0). . Zoases. : at Extend 6. | Inheritance —— expen! 'RuntimeException' or its -_ subclasses. Subclasses. _ Difference between in-built and user-defined exception: User-defined exceptions S.No. Aspect Built-in exceptions 7 Definition | Septem peonicied iy tim | Emepsjonactefined byte rogramming language. > programmer. 2 Raised Yes, automatically raised No, must be explicitly ” |_gut©matically? _byshe interpreter. piset by the programmer. L built-in exceptions User-defined exceptions 3. Compilation inherit from can inherit from ‘Exception’ _Sompilation_| _ZBaseException’. _93t subclasses. Aspect Checked exceptions Unchecked exceptions Used for general error a lored for specific error Usage handling across oe ‘scenarios in the application. applications. Example ZeroDivisionError Lolo File Not rae S rors in Java: * In Java, errors represent serious{unrecoverable problems|that occur during the execution of a program. — * Unlike exceptions, which can be caught and handled programmatically errors generally are beyond thecontrol of the application eljavalang.Error/ * Errors in Java are instances of classes that extend th class. Some common errors include: * OutOfMemoryError: This error occurs when the Java Virtual Machine Java Programming by Vikassir = * StackOverflowError: This error occurs when the execution stack grows y Le > tomy 2 * VirtualMachine Error: This is the superclass of all errors thrown by the JVM, * LinkageError: This error occurs when there is a problem with the classloading mechanism. Java Programming by Vikassir = Flow in exception handling when an exception occurs: * When an exception occurs in Java, the control flow changes to handle the exception. + Here's aGtep-by-ste; iption ff the control flow in exception handling: _21. Exception occurs: An exceptional condition occurs due to various reasons such as invalid input, arithmetic errors, file I/O errors, or other unexpected conditions. 7 'ofo unexpected conditions 22. Exception thrown: The code that detects the exceptional condition creates an obj resenting the exception and throws it using thethrow statement. Java Programming by Vikassir = * 3. Search for matching catch blocks: The Java runtime searches for a matching catch block to handle the(thrown exception.| ¢ 4. Control transfers to matching catch block: If a matching catch block is found, the control flow transfers to the(corresponding catch block skipping the remaining code in the try block. . Exception handling: The code inside the matching catch block is executed * 6. Program continues execution: After the(exception is handledthe control flow continues from the end of the catch bloc try, catch and finally block used in Exception Han try Block: * The try block contains code that(might throw an exception. * Ifan exception osama ates program will [ooklfor a corresponding fatch block to handle i * If no exception occurs, the atch block is skipped, and the program continues with the code after the finally block (if present). Syntax: pet } // code that might throw an exception Peclbeicl i Java Programming by Vikassir = catch Block: * The catch block is used to handle the exception thrown in the try block. * You can hav& multiple catch blocksto handle differenttypesof exceptions. * The first catch block that matches the type of the|thrown exception/will be executed, and others willbelignoredJ. Syntax: bs catch(ExceptionType e){ // Handle the oer } Java Programming by VikasSir finally Block: * The finally block contains code that is ‘egardless of whether an exception was thrown or caught. * It's typically used for(cleanup activitiesllike closing files, releasing resources, or ré i ‘iables. Syntax: finally ¢ a // Code that will always run, whether or not an exception occurs } public class TryCatchFinallyExample{_— Zpublic static void main(Stringf] args) { try { a Pp int result = divide(10, OJ; // This will cause an ArithmeticException System.out.printin("Result: " + result); = catch (ArithmeticException e) { System.out.printin("Caught an ArithmeticException: "+ e.getMessage)); —>} finally { 7 System.out.printin("This will always be executed."); } Le Rg cvetem.out printl ("Program continues. } ublic static int divide(int a, int b) { return a/b; f\ n S OUTPUT DISPLAY: —>Caught an ArithmeticException: / by zero >This will always be executed. Program continuess— throw Keyword: * The throw keyword is used to explicitly throw an{ excepti nin the codd. * You can use it to create andhrow an exception manually] typically within a method or a block of code when a specific error condition occurs. * When you use throw, you create an@xception objecthand hand it off to the Java runtime environmess. * The execution of the current method stops, and control is transferred to the nearest enclosing try-catch block. ern + If no try-catch block is present, the program terginates | Su > as Syntax: wv Ww w a FileOutputStream outputStream = new ieoutputstrean(outputee | String data =(Hello, won // Write data to the file = ZPytell bytes = data.getBytes(); // Convert string to byte array outputStream.close(); // Closs the Stream } — 5 “atch (IOException e) { ——e.printStackTrace(); 238 Java Programming by VikasSir Example of reading files with byte streams: import java.io.FileInputStream;_ import java.io.lOException;_— ublic class ByteStreamReadExample { _Bublic static void main(Stringl] args) { try{ _// Create a FileInputStream FileInputStream inputStream = new FileinputStrearp(“input.txt”); ) vy, _ // Read data from the file ars, int data; tee ae while ((data=inputStream.read0) =I); pore out.printin((char)data ); // convert byte to char and print. inputStream.close(); } eure (IOException e) { e.printStackTrace(); yn Java Programming by Vikassir = Character Stream: * Character streams in Java are represented by the abstract classes Reader and Writer. — * These classes define the@ssential mathodslfor readingandwriting _character data, and several subclasses provide specialized implementations for various sources and destinations, like files, buffers, endimare. Reader Class Members it read(): Reads a singl¢ character/from the input stream and returns it Casaninteger./_ buf}; Reads characters into an array; Returns the number of characters read. Java Programming by VikasSir . oe .. Ab i * int read(char{] cbuf, int off, int len): Reads up to len characters into a portion of an array starting at the specified offset off Returns the + long skip(loifg n): Skips n characters in the input stream. Returns the actual number of characters skipped. uU————_s u + GooteanfnarkSupported(): Returns true if the(mark(|and(reset() fnethods are supported by this stream. = _Astye > # Isc> rid reset(): Repositions the stream to thi ition it was at when mark() was last called-— | * void close(): Closes the stream associated with it. releases any system resources Java Programming by Vikassir = Writer Class Members __— ovoid write(int c): Writes a single character to the output stream. Void write(char[] cbuf): Writes the characters from the specified array to the output stream. a write(String str, int off, int len): Writes a portion of a string (starting at offset off and length len) to the output stream. Goi flush): Flushes the output stream, forcing any buffered output characters to be written out to theunderlyin; ream. _xzyoid close(): Closes the stream and releases any system resources associated with it. Also flushes the stream before closing. _Java Programming by VikasSir ifference between byte stream & character stream S.No. Aspect | C Byte Streams Character Stream: Used for handling binary | Used for handling textual 1. Purpose —| data like image, audios, data, such as(strings of videos etc characters.) Handle characters, 2. | Handling Data | Handle(raw binary data] | automatically encoding and decoding them — 3. Data Type | DAlwith bytes(Binary _A@eal with Characters Data) (textual data) Java Programming by Vikassir = S.No. | Aspect Byte Streams Character Streams Automatic encoding and N i i 4. | Encoding i eae = oe nBOr | decoding using specified jecoding of aka character encoding. / 5 Ria Suitable for handling non- Suitable for handling 7 textual dater ‘Textual data) 6 Efficienc: Less efficient for text-based. More efficient for text : ¥ operations~ based opsrstiGns. Thread in Java: * In Java, a thread is afightweight process Ehat allows concurrent execution of code * Java supports multithreading, which is the ability to run multiple threads simultaneously, allowing programs to perform tasks in parallel. * This is particularly useful for tasks that can beexecuted independently] like handling multiple client requests in a server or performing background computations without blocking the main application flow. Significance/importance of thread in concurrent programming: ‘Concurrency: Threads enable concurrent execution of tasks withina Java application. e Thread in Java: © Multitasking: Threads allow a Java program to perform multiple tasks simultaneously. * Responsiveness : Threads can help ensure that an application remains responsive even when@erform ing time-consuming tasks. * Parallelism: Threads can be used to achieve parallelism, where multiple tasks are executed simultaneouslyon multi-core processors.) Asynchronous programming: Threads facilitate asynchronous pene ee certain tasks to execute independently of the main program flow. * Resource sharing: Threads can share resources such as memory, files, and network connections within the same process _Java Programming by VikasSir Thread Life Cycle in Java: * In Java, a thread goes through several states from its creation to its termination. These states are collectively known as the "Thread Life Cycle." Yew (Born): * When a thread is(created usii eyword| but has not yet started, it is in the "New" state. The thread has been instantiated but thd start()/method has not been called yet. ial Runnable: * When theGtart() method is called(on a thread, it moves from the "New" state to the "Runnable" state~ * In this state, the thread is ready to run and is waiting for Feu time. Running: * When a thread from the "Runnable" state is selected by the thread schedulerjto execute, it moves into the "Running" state. * This is when the thread's run() method is ee New Thread. resume) notify¢] Idle Thread (Not runnable) Thread Blocked (Non-Runnable): * Athread enters the "Blocked" state when it is alive but unable to run due to some conditio: * Common feieoen ites waiting for_1/O operations to complete, waiting to _acquire a lock, or waiting for another thread toyetease a resource] — Waiting: 7 * Athread enters the "Waiting" state when it is waiting indefinitely for another thread to perform a particular action (e.g., calling notify() or notifyAll() on a lock that the thread is waiting for). Terminated (Dead)p 7 * Athread enters the "Terminated" state when it ha Finished executingjits run() method. Once a thread is in this state, it cannot be restarted. SS * In Java, a thread can be created in two main ways: — A. Extending the(hread class] * You can create a class that extends the (Thread classhnd overrides the(rund)] method. * The run() method contains the code that will be executed in the(new thread] example: Zi u class MyThread extends Thread { public void run() { System.out, printinThis is anew thread." GP a public class (Mai —Public static void rae ingl] args) { MyThread my Thread = ridw néw MyThread(y~ myThread.start0);}} — implementing the Runnable interfac * You can create a class that implements the Runnable interface And overrides the Gant metho) od. 7 7 + Then, you can create an instance of Thread and pass an instance of your class toits —— example: yy _class MyRunnable impi¢mentdunnebtalt public void run() { System.out.printin("This is a new thread."); pub Maint seul lic static void eee args) { iw Thread(new MyRunnable()); twa start; ny Difference between threads and processes: S Aspect Thread Process A thread is the smallest unit of execution within a process. A process is an independent program in execution with its own memory space. Memory Threads share the same memory space within a process. Each process has its own separate memory spgser— Communication Communication between threads is easy and fast since they share the ‘Communication between processes requires inter-process communication (IPC) mechanisms, _ which are more complex and slower. Difference between threads and processes: Aspect Thread Process Threads are generally lighter and Processes are heavier and take more Creation faster_to create. e and resources to create. Threads within a process are Processes are independent of each Dependency | depen ach other and share : other, with their own resources. the process's resources. nasi Threads share the resources of the | Each process has its own resources . parent process (e.g., file handles, Allocation memory). and does not share them with other processs® Difference between threads and processes: S Aspect Thread Process Multiple threads within the same | Multiple processes can also execute Execution concurrently, but they are Isolated process can execute concurrently. | Soncurrently, from each other, Ifa thread crashes, it may affect the | Ifa process crashes, it does not Crash Impact entire process, directly affect other processes. Threads are used for tasks that require parallel execution within the Procesems sts lieed for niniing Use Case eek separate applications or isolated same application, like handling Multiple requests ina server. tasks that require full independence. Synchronization in java: * Thread synchronization in Java is a way td control the access)of multiple threads to shared resourcesito avoid conflicts and ensure data consistency. — * Java provides theynchronized keywordko achieve thread synchronization. When a method or a block of code is marked as synchronized, only one thread€an execute that code at a time. * Other threads trying to access the same(code will be blocked until the first thread finishes * This synchronization is implemented in Java with a concept called monitors or locks. * There are two synchronizations in Java mentioned below: (A.) Process Synchronization. (B.) Thread Synchronization. Process Synchronization in Java: * Process Synchronization is a technique used to(coordinate the execution o It ensures that the shared resources/are safejand in “order. Jee aT 4 Fr 7 z Thread Synchronization in Jav: * Thread Synchroniz: execution of the threads in a mult lg 3 * There are two types of thread synchronization are mentioned below: * Mutual Exclusive —_ * Cooperation (Inter-thread communication in Java) Synchronized Block: public void myMethod() { synchronized (this) { // 'this' refers to the current object // Code that needs to be Ee } i } S Thread Prio! + Every Java thread has a(fhread priorit) (from MIN_PRIORITY to MAX_PRIORITY) that helps the operating system determine the order in eee which threads are scheduled. * Itis represented as integer value ranging from 1 to 10, — * By default, every thread is given priority NORM PRIORITY(constant of()) © The minimum priority that a thread can have, with afvalue of 1) * The maximum priority that a thread can have, with a(falue of 10] (0 Ly? y “Oe @

You might also like