What to do when you find out your research result is wrong because it's based on wrong methods/results, after years of works? This is not my current situation. However I've heard similar stories from different people (along with my own past experience) a few times. Therefore I want to ask a general question(the title).

For example, suppose you're a graduate student in one of the following scenarios


You believe you prove a theorem but later find out it's wrong because one of the lemma/theorem you cite from another published paper is wrong.
You spend long time setting up experiments and finding out an published experiment result is not reproducible and is likely to be wrong. 
You rely on co-workers' code to run simulations but it turns out that there are errors in the code that makes the simulation inaccurate, therefore the conclusion based on that is wrong.


and let's further assume you find out those problems when it's closed to advancement or dissertation time of graduate study. You've spent a few years, only to get a faulty result that is not likely to advance you to the next stage of a researcher. 

Q. Are these scenarios hopeless (i.e. a student in that scenario must terminate graduate study)? Should the student be the only one responsible for the issue?

If not, what's the best thing one can do in those scenarios?

If so, how to prevent them? (You can still answer this question even if your answer to Q. is no.)

Highly appreciated if anyone can discuss this from either student's or advisor's point of view.
One thing to consider is that showing fault in an "established" result is, in itself, an important result. If a student spent years working on a project, only to find that the results from their new work disprove earlier accepted results, that's worth telling other researchers (i.e. publishable). Especially considering there's probably dozens of other graduate students all working off those same results until someone tells them the results are not reliable. In fact, my father, an emeritus professor of mathematics, lists "counter-examples" as one of his areas of research. 

In the case of proofs and lemmas (i.e. case 1), this is clearly publishable. In the case of experiments, it's a little harder: you would need to make a strong case for your new experiment being substantial evidence that the previous results were wrong, rather than you just botched your experiment. But if you can make a solid case, it is well worth publishing. 

Sadly, the third case is not so good for the student. Assuming the student's colleague has not published yet, the research community does not benefit much from the student saying "hey I just realized my friend messed up". They should still tell their colleague and advisor so that the situation is communicated.