[Go to site: main page, start]

0% found this document useful (0 votes)
2 views11 pages

Java Chapter 5

The document explains the concept of exceptions in Java, differentiating between errors and exceptions, and categorizing exceptions into checked, unchecked, and errors. It outlines the Java exception handling mechanism using keywords like try, catch, finally, throw, and throws, and provides examples of common exceptions and their handling. Additionally, it discusses string creation, concatenation, and the importance of exception handling in maintaining the normal flow of a program.

Uploaded by

sujalshrestha9272
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)
2 views11 pages

Java Chapter 5

The document explains the concept of exceptions in Java, differentiating between errors and exceptions, and categorizing exceptions into checked, unchecked, and errors. It outlines the Java exception handling mechanism using keywords like try, catch, finally, throw, and throws, and provides examples of common exceptions and their handling. Additionally, it discusses string creation, concatenation, and the importance of exception handling in maintaining the normal flow of a program.

Uploaded by

sujalshrestha9272
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
n Handling Error/Ex ns [2 Hr: ‘An exception is an unwanted or unexpected event, which occurs during the execution of a programi.e. at run time, that disrupts the normal flow of the program’s instructions. Error vs Exception Error: An Error indicates serious problem that a reasonable application should not try to catch. Exception: Exception indicates conditions that a reasonable application might try to catch. ‘An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these ‘exceptions are to be handled. ‘An exception can occur for many different reasons. Following are some scenarios where an ‘exception occurs. + Auser has entered an invalid data + Afile that needs to be opened cannot be found. + Anetwork connection has been lost in the middle of communications or the JVM has run out of memory. Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. Based on these, we have three categories of Exceptions. You need to understand them to know how exception handling works in Java. + Checked exceptions ~ A checked exception is an exception that is checked (notified) by the compiler at compilation-time, these are also called as compile time exceptions. These exceptions cannot simply be ignored; the programmer should take care of (handle) these exceptions. + Unchecked exceptions - An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. + Errors - These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation. Prepared by: Raju Poudel [MCA] 53 Hierarchy of Java Exception classes ‘The [Link], Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below: Prepared by: Raju Poudel (MCA] 54 Java Exception Keywords There are 5 keywords which are used in handling exceptions in Java. Keyword | Description try The "try" keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone. catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later. finally | The “finally” block is used to execute the important code of the program. It is executed whether an exception is handled or not. throw | The "throw" keyword is used to throw an exception. throws | The "throws" keyword is used to dediare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature. Java Exception Handling Example Let's see an example of Java Exception Handling where we using a try-catch statement to handle the exception. public class JavaExceptionExample{ public static void main(String args{1){ trv{ //code that may raise exception int data=100/0; }eatch (ArithmeticException e) { [Link](e); + //rest code of the program [Link]("rest of the code..."); + + ‘Output: Exception in thread main [Link],ArithmeticException:/ by zero rest of the code.. Prepared by: Raju Poudel [MCA] 55 Common Scenarios of Java Exceptions There are given some scenarios where unchecked exceptions may occur. They are as follows: 1) Ascenario where ArithmeticException occurs If we divide any number by zero, there occurs an ArithmeticException. int a=50/0;//ArithmeticException 21. A scenario where NullPointerException occurs If we have a null value in any variable, performing any operation on the variable throws 2 NullPointerException. String s=null; ‘[Link]([Link]());//NullPointerException 21 Ascenario where NumberFormatException occurs The wrong formatting of any value may occur NumberFormatéxception. Suppose | have a string variable that has characters, converting this variable into digit will occur NumberFormatException 4) A scenario where ArrayindexOutOfBoundséxception occurs If you are inserting any value in the wrong index, it would result in ArrayindexOutOfBoundsException as shown below: int af]=new int{5]; a[10]=50; //ArrayIndexOutofBoundsException Java finally block Java finally block is a block that is used to execute important code such as closing connection, stream ete. Java finally block is always executed whether exception is handled or not. Java finally block follows try or catch block. public class TestFinallyBlock2{ public static void main(String argsf]){ try int data=25/0; [Link](data); > catch(ArithmeticException e){ System. [Link](e); > finally{ System. out printin(“finally block is always executed"); Prepared by: Raju Poudel [MCA] 56 + [Link](“rest of the code. + + Output: Exception in thread main [Link]:/ by zero finally block is always executed rest of the code... Java Multi-catch block A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block. Ata time only one exception occurs and at a time only one catch block is executed. All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception. public class MultipleCatchBlock1 { public static void main(String[] args) { tryt int a[]=new int{5]; a[5}=30/0; } catch(ArithmeticException e) { [Link]("Arithmetic Exception occurs"); + catch(ArrayIndexOutOfBoundsException e) € ‘System. [Link]("ArrayIndexOutofBounds Exception occurs"); , ‘catch(Exception e) t [Link]-printin("Parent Exception occurs"); + [Link]("rest of the code"); Output: Arithmetic Exception occurs rest of the code Prepared by: Raju Poudel [MCA] 87 public class MultipleCatchBlock2 { public static void main(String[] args) { tryt int a[]=new int(5}; [Link](a[10}); , catch(ArithmeticException e) { [Link]("Arithmetic Exception occurs"); y catch (ArrayIndexOutOfBoundsException e) € ‘[Link]("ArrayIndexOutOfBounds Exception occurs"); + catch(Exception e) € [Link]("Parent Exception occurs"); , ‘[Link] printin("rest of the code"); + + Output: ArrayIndexOutOfBounds Exception occurs rest of the code Java Nested try block The try block within a try block is known as nested try block in java. Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested. Syntax: try { statement 1; statement 2; try { statement 1; statement 2; } Prepared by: Raju Poudel [MCA] 58 catch(Exception e) , } catchiException e) { class Excep6{ public static void main(String args[]){ try{ tryf [Link](“going to divide"); int b =39/0; }eatch(Arithmeticexception e){ [Link](e); + trv int a[]=new int{5]; a[S}=4; }eatch(ArrayindexOutOfBoundsException e){ [Link]-printin(e); + ‘[Link]("“other statement); }eatch(Exception e){ [Link](“handeled”); + [Link](“normal flow... + + Prepared by: Raju Poudel [MCA] 59 Java throw keyword The Java throw keyword is used to explicitly throwan exception. ‘We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception. The syntax of java throw keyword is given below. throw new IOException("sorry device error); Example: In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote. public class TestThrow1{ static void validate(int age){ if(age<18) throw new ArithmeticException("not valid"); else ‘[Link]("welcome to vote"); + public static void main(String args{]){ validate(13); [Link]("rest of the code. Qutput: Exception in thread main [Link]:not valid Java throws keyw The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained. Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing checkup before the code being used. ‘Syntax of java throws: return_type method_name() throws exception_class_name{ //method code + Prepared by: Raju Poudel [MCA] 60 Example of Java throws import [Link].I0Exception; class Testthrows1{ void m()throws IOException{ throw new IOException(“device error");//checked exception } void n()throws IOException{ m0; + void p(){ try nO; Yeatch(Exception e){ ‘[Link](“exception handled” + + public static void main(String arasf1){ Testthrows1 obj=new Testthrows1(); ob1-P0; ‘[Link]. printin(‘normal flow..."); normal flow... Difference between throw and throws in Java Ne throw throws Java throw keyword is used to| Java throws keyword Is used to dedare explicitly throw an exception. an exception. 2)] Checked exception cannot be | Checked exception can be propagated propagated using throw only. with throws. 3)| Throw is followed by an instance. Throws is followed by class. 4)| Throw is used within the method. Throws is used with the method signature. 5)] You cannot throw ~— multiple |__ You can declare multiple exceptions e.g. exceptions. public void method()throws, TOException, SQLException. Prepared by: Raju Poudel [MCA] 61 Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The [Link] class is used to create a string object. In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example: char{] ch={'J'/2'/'V/'2'/t'/p/0,"'/0"/}; String s=new String(ch); is same as: String s="javatpoint"; There are two ways to create String object: 1. Bystring literal 2. By new keyword 2) String Literal Java String literal is created by using double quotes. For Example: String s="welcome"; Each time you create a string literal, the JVM checks the "string constant pool” first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool. For example: String s1="Welcome"; String s2="Welcome";//It doesn't create a new instance 2) By new keyword String s=new String(“Welcome" ;/[ereates two objects and one reference variable Java String Example public class StringExample{ public static void main(String arast1}{ String s1="java";//creating string by java string literal char ch{J={'s',t)'r,'1,'n',9''S'}; String s2=new String(ch);//converting char array to string String s3=new String(“example");//creating java string by new keyword [Link](s1); [Link](s2); [Link](s3); » Qutput btringe example Prepared by: Raju Poudel [MCA] 62 ‘String Length The length of a string is the number of characters that it contains. To obtain this value, call the length( ) method, shown here: int length( ) The following fragment prints char chars[] = { ‘a’, 'b’, String s = new String(chars): ‘[Link]([Link](): since there are three characters in the string s: Concatenation of String The following fragment concatenates three strings: String ag String s = "He is" + age +" years old.’ [Link](s); This displays the string “He is 9 years old.” ‘One practical use of string concatenation is found when you are creating very long strings. Instead of letting long strings wrap around within your source code, you can break them into smaller pieces, using the + to concatenate them. Here is an example: // Using concatenation to prevent long lines. class ConCat { public static void main(String args()) { String longStr = "This could have been "+ very long line that would have " + “wrapped around. But string concatenation "+ “prevents this.”; [Link](longStr); } } String Concatenation with Other Data Types You can concatenate strings with other types of data. For example, consider this slightly different version of the earlier example: int age = 9; String s= "He is" + age +" years old."; ‘[Link](s); In this case, age is an int rather than another String, but the output produced is the same as before. This is because the int value in age is automatically converted into its string representation within a String object. This string is then concatenated as before. Be careful when you mix other types of operations with string concatenation expressions, however, you might get surprising results. Consider the following: String s = "four:" +2 +2; System. [Link](s); ‘This fragment displays four: 22 rather than the fo Prepared by: Raju Poudel [MCA] 63

You might also like