Skip to main content

Posts

Showing posts with the label Exception Handling

How does exception handling work in Java?

1.It separates the working/functional code from the error-handling code by way of try-catch clauses. 2.It allows a clean path for error propagation. If the called method encounters a situation it can't manage, it can throw an exception and let the calling method deal with it. 3.By enlisting the compiler to ensure that "exceptional" situations are anticipated and accounted for, it enforces powerful coding. 4.Exceptions are of two types: Compiler-enforced exceptions, or checked exceptions. Runtime exceptions, or unchecked exceptions. Compiler-enforced (checked) exceptions are instances of the Exception class or one of its subclasses — excluding the RuntimeException branch. 

How To Deal with Array Exception in Java

Remember that array indexes start at 0. So, for an array with five locations, the indexes would be 0,1,2,3,4. Check that FOR loops and the results of any calculated indexes take this into account. Also, make sure that a value is checked before it is incremented. String[] bob = new String[10]; for(int i=1 ; i<10 ; i++) The index should start at 0, and go to 9 { bob[i]="bob" The error will point to this line } In the first program, the error is caused by the FOR loop having the wrong parameters. This causes the error in another place.

How differently does Java handle checked and unchecked exceptions?

If a method may throw checked exceptions, the calling code must handle the exception by either catching it or by declaring in the signature of the method (as throws). Unchecked exceptions do not have to be handled by the calling code. If a method might throw a checked exception, it must be declared in the signature of the method. Unchecked exceptions do not have to be listed in the method signature. When to use checked exceptions and unchecked exceptions? Please visit Best Practices for Exception Handling .

Java Exceptions Interview Questions - Latest

Explain the user defined Exceptions? User defined Exceptions are custom Exception classes defined by the user for specific purpose. A user defined exception can be created by simply sub-classing an Exception class or a subclass of an Exception class. This allows custom exceptions to be generated (using throw clause) and caught in the same way as normal exceptions. Example: class CustomException extends Exception { } What classes of exceptions may be caught by a catch clause? A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. Errors are generally irrecoverable conditions What is the difference between exception and error? Error's are irrecoverable exceptions. Usually a program terminates when an error is encountered. What is the difference between throw and throws keywords? The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as an a...

How Can I Catch All Possible Exceptions in Java?

-- All exceptions come from the "mother class" called java.lang.Throwable and one of two subclasses called java.lang.Error and java.lang.Exception . A block of code that is executed when an exception occurs is called an Exception handler . By catching java.lang.Throwable , it is possible to handle all unexpected conditions. ... try { } catch(Throwable e) { ... } ... There are some special exceptions that used by the JVM, those are the sub-classes of java.lang.Error . We are not suppose the catch them in our real code and we usually catch java.lang.Exception for all application and runtime exceptions. ... try { } catch(Exception e) { ... } ...

How differently does Java handle checked and unchecked exceptions?

-- If a method may throw checked exceptions, the calling code must handle the exception by either catching it or by declaring in the signature of the method (as throws). Unchecked exceptions do not have to be handled by the calling code. If a method might throw a checked exception, it must be declared in the signature of the method. Unchecked exceptions do not have to be listed in the method signature. When to use checked exceptions and unchecked exceptions? Please visit Best Practices for Exception Handling .

What are differences among throw, throws, and Throwable?

-- In Java, all error's and execption's class are drieved from java.lang.Throwable class. It is the top of the hierarchy of classes of error and exceptions. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. throws is a post-method modifier and specifies which execptions may be thrown by the method. If they are checked exceptions, the compiler will guarantee the code invoking that method must catch these checked exceptions.  throw statement is used to throw an error or exceptions. throw statement requires a single argument: a instance of any subclass of the Throwable class or Throwable class. Executing throw statement triggers the JVM to throw this exception and causes an exception to occur.

How to avoid an java.util.ConcurrentModificationException with ArrayList?

You need to add/delete an item in an ArrayList when you are iterating the list. You will receive the java.util.ConcurrentModificationException exception. For example, the following code will throw an exception after adding an item into list: public class Sample {   public static void main(String[] args) {     List   iList = new ArrayList ();     for (int i = 0; i != 100; i++)       iList.add(i);     int addValue = 1000;     for (Integer i: iList) {       if (i%10 == 0) {         iList.add(addValue++);       }     }   } To avoid java.util.ConcurrentModificationException exception, we can add an item through the iterator of list. If we do the same as the above code, the next access item in list via the iterator will generate the same exception. public class Sample {   pub...

What is the difference between compile time error and run time error?

At compile time, when the code does not comply with the Java syntactic and semantics rules as described in Java Language Specification (JLS), compile-time errors will occurs. The goal of the compiler is to ensure the code is compliant with these rules. Any rule-violations detected at this stage are reported as compilation errors. The best way to get to know those rules is to go through all the sections in the JLS containing the key words "compile-time error". In general, these rules include syntax checking: declarations, expressions, lexical parsing, file-naming conventions etc; exception handling: for checked exceptions; accessibility, type-compatibility, name resolution: checking to see all named entities - variables, classes, method calls etc. are reachable through at least one of the declared path; etc. The following are some common compile time errors:

Can private method be overridden?

The private methods are not inherited by subclasses and you cannot be overridden by subclasses. According to Java Language Specification ( 8.4.8.3 Requirements in Overriding and Hiding ), "Note that a private method cannot be hidden or overridden in the technical sense of those terms. This means that a subclass can declare a method with the same signature as a private method in one of its superclasses, and there is no requirement that the return type or throws clause of such a method bear any relationship to those of the private method in the superclass." What does it mean? It means you can have a private method has the exact same name and signature as a private method in the superclass, but you are not overriding the private method in superclass and you are just declaring a new private method in the subclass. The new defined method in the subclass is completely unrelated to the superclass method. A private method of a class can be only ...

Why am I getting unreported exception when the super class default constructor has a 'throws' clause?

class Super { public Super() throws Exception { System.out.println("Super Class"); } } public class Sub extends Super { public static void main(String[] args) throws Exception { Sub s = new Sub(); } } Compile it and you have compile-time error: Sub.java:6: unreported exception java.lang.Exception in default constructor public class Sub extends Super { 1 error Here is a Sun's Bug Report which can answer this quesion: When a superclass constructor has a non-empty throws clause, subclasses must define an explicit constructor with an appropriate throws clause, as a default constructor has no throws clause. (This is stated in JLS 2e 8.8.7, ruling out the xxxxx alternative of copying the superclass constructor's throws clause.

Why am I getting unreported exception when the super class default constructor has a 'throws' clause?

class Super { public Super() throws Exception { System.out.println("Super Class"); } } public class Sub extends Super { public static void main(String[] args) throws Exception { Sub s = new Sub(); } }   Compile it and you have compile-time error:   Sub.java:6: unreported exception java.lang.Exception in default constructor    public class Sub extends Super { 1 error Here is a Sun's Bug Report which can answer this question: When a superclass constructor has a non-empty throws clause, subclasses must define an explicit constructor with an appropriate throws clause, as a default constructor has no throws clause. (This is stated in JLS 2e 8.8.7, ruling out the xxxxx alternative of copying the superclass constructor's throws clause. Currently, the compiler generates a default constructor with an empty throws clause, and then generates an error message. Unfortunately, the offending call, the implicit call to the...

DB2 Error: com.ibm.db2.jcc.b.SqlException: DB2 SQL Error: SQLCODE=-727, SQLSTATE=56098, SQLERRMC=2;-551;42501;SPILTODB2|SELECT|VAJ.CODES, DRIVER=3.53.95

Problem : DB2 Error: com.ibm.db2.jcc.b.SqlException: DB2 SQL Error: SQLCODE=-727, SQLSTATE=56098, SQLERRMC=2;-551;42501;SPILTODB2|SELECT|VAJ.CODES, DRIVER=3.53.95 Solution : The UserID which is trying access the table does not have proper previleges / credentials to access the table. So assign correct previleges to the UserId and try, it will work out.

Java Exceptions Handling

Explain the user defined Exceptions? User defined Exceptions are custom Exception classes defined by the user for specific purpose. A user defined exception can be created by simply sub-classing an Exception class or a subclass of an Exception class. This allows custom exceptions to be generated (using throw clause) and caught in the same way as normal exceptions. Example: class CustomException extends Exception { } What classes of exceptions may be caught by a catch clause? A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. Errors are generally irrecoverable conditions What is the difference between exception and error? Error's are irrecoverable exceptions. Usually a program terminates when an error is encountered. What is the difference between throw and throws keywords? The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown ...

Exceptions Handling in Java

Why is it not advisable to catch type " Exception" ? Exception handling in Java is polymorphic in nature. For example if you catch type Exception in your code then it can catch or throw its descendent types like IOException as well . So if you catch the type Exception before the type IOException then the type Exception block will catch the entire exceptions and type IOException block is never reached. In order to catch the type IOException and handle it differently to type Exception , IOException should be caught first (remember that you can't have a bigger basket above a smaller basket). The diagram above is an example for illustration only. In practice it is not recommended to catch type " Exception" . We should only catch specific subtypes of the Exception class. Having a bigger basket (i.e. Exception ) will hide or cause problems. Since the RunTimeException is a subtype of Exception, catching the type Exception will catch all the run time exceptions (like...

Discuss the Java error handling mechanism? What is the difference between Runtime (unchecked) exceptions and checked exceptions? What is the implication of catching all the exceptions with the type “Exception”?

Errors: When a dynamic linking failure or some other "hard" failure in the virtual machine occurs, the virtual machine throws an Error. Typical Java programs should not catch Errors. In addition, it's unlikely that typical Java programs will ever throw Errors either. Exceptions: Most programs throw and catch objects that derive from the Exception class. Exceptions indicate that a problem occurred but that the problem is not a serious JVM problem. An Exception class has many subclasses. These descendants indicate various types of exceptions that can occur. NegativeArraySizeException indicates that a program attempted to create an array with a negative size. One exception subclass has special meaning in the Java language: RuntimeException. All the exceptions except RuntimeException are compiler checked exceptions. If a method is capable of throwing a checked exception it must declare it in its method header or handle it in a try/catch block. Failure to do so raises a comp...

How to avoid and fix the NullPointerException in Java

The solutions mentioned below are given by different people. Check it out which will work out for your application. Solution 1: Null Pointer Exceptions usually occur when you try to use an object that has been declared but not yet instantiated. Let's say you declared an ArrayList in your code, e.g. private ArrayList someList. If you attempt to use someList without first instantiating the list: someList.add(object o); without first calling someList = new ArrayList(), you would get a null pointer Exception. Fixing null pointer exceptions is code dependent. There is no overall solution: it depends on what caused the exception. Solution 2: Don't invoke operations on null objects. You can test for the reserved word null before calling a method. Sometimes it is valid for a variable to contain a null reference. In order to "fix" a null variable you need to look at where you think you should be constructing the object in question and see what's going wrong...